Upload
-
The user selects a file to be uploaded on the page, and then submit the request to the Servlet
-
Servlet receives the request, parse the user to upload a file, and then store the file to the server
<form action="Servlet" method="post" enctype="multipart/form-data"> <input type="file" name="file" /><br /><br /> <input type="submit" value="上传" /> </form>
-
Form method attribute must post
-
Form enctype attribute must multipart / form-data
-
Note: Servelet
- When enctype = "multipart / form-data", and then use getParamter () acquired content is always empty.
- Need to introduce analytical parameters and file request, this tool is commons-fileupload.
Its role is to be parsed from the request object, flow parameters, and upload request sent by the user.
commons-fileupload package depends commons-io, two packets need to import .
-
DiskFileItemFactory
-
Factory class for creating ServletFileUpload, set caching
-
This class is generally used as a constructor to create the instance
-
method:
-
public void setSizeThreshold (int sizeThreshold): used to set the size of the cache files (default 10KB)
-
public void setRepository (File repository): used to set the cache file location (the default system cache directory)
-
-
-
ServletFileUpload
-
This class is used to resolve the request object so as to acquire transmission parameters of the user request (including the common parameters and parameter files)
-
This class has parameters need to call the constructor creates an instance, the constructor requires a parameter as DiskFileItemFactory
-
method:
-
List public <FileItem> the parseRequest (the HttpServletRequest request): parsing the request object parameter acquisition request, returns a List, a List is stored in a FileItem objects, an object representing a request parameter.
-
public void setFileSizeMax (long fileSizeMax): set a size limit of a single file, in units of B. If the uploaded file exceeds the limit, it will () throws an exception FileSizeLimitExceededException in parseRequest.
-
public void setSizeMax (long sizeMax): limiting the total size of the requested content, in units of B. If the uploaded file exceeds the limit, it will () throws an exception SizeLimitExceededException in parseRequest.
-
-
-
FileItem
-
Such parameters and files for the package sent by the user, the information is transmitted to the user will be packaged into a FileItem objects, we get information request parameter or upload files through the object.
-
We do not have to manually create the class, parses request by the ServletFileItem return.
-
method:
-
String getFieldName (): Gets the table name of the individual, that is, the value of the name attribute of input among.
-
String getName (): Gets the name of the uploaded file, a common request parameter is null.
-
String getString (String encoding): access to content, encoding parameter to specify a character set.
① If it is a file, the file stream is converted into a string.
② If the request parameters, the acquisition value of the request parameter.
-
boolean isFormField (): determines whether the current package is common FileItem request parameter, or a file.
① If the return to normal parameters: true
② If the file parameter is returned: false
-
String getContentType (): Gets the MIME type of the uploaded file
-
long getSize (): Gets the size of content
-
-
// create a factory class DiskFileItemFactory Factory = new new DiskFileItemFactory (); // Create the request parser ServletFileUpload fileUpload = new new ServletFileUpload (Factory); // set the size of a single file upload fileUpload.setFileSizeMax (1024 * 1024 *. 3 ); // provided the total size of the upload file fileUpload.setSizeMax (* 1024 * 1024 * 10. 3 ); // set the encoding of the content in response to the response.setContentType ( "text / HTML; charset = UTF-. 8" ); the try { // parse request information obtaining a set of FileItem List <FileItem> items = fileUpload.parseRequest (Request); // iterate set for(The FileItem FileItem: items) { // If an ordinary table item IF (fileItem.isFormField ()) { // Get Parameter Name String the fieldName = fileItem.getFieldName (); // Get parameter value String value = fileItem.getString ( "UTF-. 8" ); System.out.println (the fieldName + "=" + value); // if the item is a file table } the else { // get file name String fileName = fileItem.getName (); // Get upload path String realPath = getServletContext () .getRealPath ( "/ the WEB-INF / upload" ); // check upload folder exists, if it does not exist create file f = new new file (realpath); IF (! f.exists ()) { f.mkdir(); }; // to avoid duplicate names to generate the file name as a prefix uuid String = UUID.randomUUID prefix () toString () Replace ( "-", ".". ); // write files to the server fileItem.write ( new new file (realpath + "/" + prefix + "_" + fileName)); // clear the file cache fileItem.delete (); }
} } The catch (Exception E) { IF (E the instanceof the SizeLimitExceededException) { // total file size exceeds the limit response.getWriter () print ( "total upload file size can not exceed 30M." ); } The else IF (E the instanceof FileSizeLimitExceededException) { // single file size exceeds the limit response.getWriter () print ( "upload single file size can not exceed 3M." ); } } . response.getWriter () Print ( "upload successfully");
-
The server sends as a stream file to the browser.
-
At the same time transmit streams also need to set some response headers to tell the browser to download the information.
-
Specific response header as follows:
-
Content-Type
-
MIME type of file to download
-
Can. GetMimeType (String file) obtained by servletContext
-
It can also be directly manually specify
-
使用response.setContentType(String type);
-
Response header style: Content-Type: audio / mpeg
-
-
Content-Disposition
-
The name of the downloaded file, the main role is to provide a default user name
-
By response.setHeader ( "Content-Disposition", disposition) Set
-
Response header style: Content-Disposition: attachment; filename = xxx.mp3
-
-
Content-Length
-
The length of the downloaded file, a file for set strengths (not necessarily)
-
. SetContentLength (int len) set by the response.
-
After setting styles: Content-Length: 3140995
-
-
-
-
Next, the need to read files on the hard disk in the form of an input stream
-
FileInputStream is = new FileInputStream(file);
-
The flow is what we will be sent to a Content Browser
-
-
Obtaining an output stream to the response, the file (input stream) to the browser through the stream
-
Acquiring output streams: ServletOutputStream out = response.getOutputStream ();
-
-
Steps to Demonstrate
The following steps are written in the same Servlet's doGet () method
1. Obtain stream files:
. String realPath = getServletContext () getRealPath ( "/ WEB-INF / mp3 / Chinese words .mp3" ); // get the file File object File File = new new File (realpath); // get the input stream file FileInputStream in = new new FileInputStream (File);
2. Get header information:
// get MIME file information String contentType = getServletContext () getMimeType (realpath);. // Set the downloaded file name String filename = "zhongguohua.mp3" ; // Create a Content-Disposition Information String disposition = "attachment; filename = "+ filename; // Get file length Long size file.length = ();
3. Set the header information
// Set the Type-the Content the response.setContentType (contentType); // set-Disposition the Content response.setHeader ( "the Content-Disposition" , Disposition); // set file length response.setContentLength (( int ) size);
4. Send file
// Get response output stream by outputting the content to the browser for the ServletOutputStream OUT = response.getOutputStream (); // the file input stream through the output stream byte [] B = new new byte [1024 ]; int len = 0 ; the while ((len = is.read (B))> 0 ) { out.write(b, 0, len); } // Do not forget to close the input stream, the output stream is processed by Tomcat ourselves, we do not have to manually close is.close ();
Chinese file name garbled problem. The solution to this problem is simple, to encode the file name in the file name after the acquisition:
filename = java.net.URLEncoder.encode(filename,"utf-8");
Firefox special needs special handling it.
1. The first to obtain client information (User-Agent header information by acquiring request)
String ua = request.getHeader("User-Agent");
2. Then determine your browser version, do different treatment
// determines whether the client is Firefox IF (ua.contains ( "Firefox" )) { // if using BASE64 encoded Firefox filename = "=?. 8-UTF? B?" + New new Base64Encoder (). Encode (filename. getBytes ( "UTF-8")) + "=?" ; }else{ //否则使用UTF-8 filename = URLEncoder.encode(filename,"utf-8"); }
String string = new String("你好.jpg".getBytes("gbk"), "iso8859-1");