1. Upload (cannot use Baseservlet):
The role of uploading, slightly
Upload requirements (required for forms and Servlets):
1. You must use the form, not the hyperlink, method= "Post" file obviously can't get the parameters in the back
2. You must use the multipart form data enctype= "Multipart/form-data"
3. The form must be added file form item input type= "file" name= "xxx"
4. All the forms with files (all!) ) data cannot be obtained with the GetParameter () method, with Enctype
You cannot use this method, but instead use getInputStream () to return the entire request body
Body of the multi-part form:
1. One form item one part
2. A part contains the request header, the blank line, the request body
3. Ordinary form items: a head content-disposition name= "xxx" is the name of the form item, the body is the value of the table item
File Form item: Contains two headers: content-disposition name= "xxx", form item name, and a filename= "xxx" i.e. file name
Content-type: The MIME type of the uploaded file
Commons-fileupload.jar pack comes on, he has an IO dependency package
It can help us to parse the data in the request, a form of data encapsulated in an Items object, call Fileitems method can
Upload three steps:
1. Factory Diskfileitemfactory
2. Parser Servletfileupload
3. Form Item Fileitem
Create a factory with a constructor
To create a parser for a factory, you can new
Get the table item using the parser to get the collection data
To a request list<fileitem> fileitemlist = sfu.parserequest (request);
Give a small example:
JSP page:
<%@ page language= "Java"Import= "java.util.*" pageencoding= "UTF-8"%><%@ taglib prefix= "C" uri= "Http://java.sun.com/jstl/core"%><%String Path=Request.getcontextpath (); String BasePath= Request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >User name:<input type= "text" name= "username"/><br/>Photo:<input type= "file" name= "photo"/><br/> <input type= "Submit" value= "Upload"/> </form> < /body>
Servlet page:
PackageCn.itacast.servlet;ImportJava.io.File;Importjava.io.IOException;Importjava.util.List;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.commons.fileupload.FileItem;Importorg.apache.commons.fileupload.FileUploadException;Importorg.apache.commons.fileupload.disk.DiskFileItemFactory;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload; Public classUploadServlet2extendsHttpServlet { Public voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {request.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8"); //upload three steps, see notesDiskfileitemfactory factory =Newdiskfileitemfactory (); Servletfileupload SFU=Newservletfileupload (Factory); Sfu.setfilesizemax (100*1024); Try{List<FileItem> fileitemlist =sfu.parserequest (Request); Fileitem F1= Fileitemlist.get (0); Fileitem F2= Fileitemlist.get (1); System.out.println ("Normal form item:" +f1.getfieldname () + "=" +f1.getstring ("UTF-8")); System.out.println ("File Form item:"); System.out.println ("File type:" +F2.getcontenttype ()); File File=NewFile ("F:/2.jpg"); F2.write (file); }Catch(Exception e) {e.printstacktrace (); } }}
Details of the upload:
1. The file must be saved to Web-inf (of course c.d.e, but strongly not recommended), in order not to allow direct access to the browser
2. File name Related: Some are absolute path, need to be cut (cut file name come over),
Some browsers (IE6, surfing, etc.)
Sting filename = F2.getname ();
int index = filename.lastindexof ("\ \");
if (Index! =-1) {
String filename1 = filename.substring (index+1);
}
3. Garbled problem: File name garbled and so on to FileUpload to deal with, when used to tell it code, request.setcharaterencoding ("UTF-8");
FileUpload will automatically invoke processing
Of course, the parser also provides a way
Servletfileupload.setheaderencoding (); Internal method, high priority
4. Dealing with duplicate names, adding a prefix (UUID) for each file name, dealing with duplicate problems
filename = commonutils.uuid () + "_" +filename; Use the customer's file name and add our non-repeating prefix
5. Directory Scatter problem: Cannot store too many files under one folder
The first letter is broken: If the file name is called Abc.txt, it is saved to the B directory, does not exist to create
The limitation is also obvious, Chinese and so on too many complex
time Break: Use the current date as a directory, one folder per day
limitations: Sometimes the weekend catalog is full and the working day is empty
Hash Break (recommended): Any object has a hashcode () method that gets an int value
Get hash value
Convert int value to hexadecimal
gets the first two bits of hexadecimal used to generate the directory
directory is two layers, such as file name 1a2b3c Generate directory 1/a/file name
the range of up to int can be generated, 4 bytes 32 bits, 8-bit hexadecimal
up to 4.2 billion
limitations embodied in the manual do not know where to find trouble, but the computer is very clear
Cut file name, plus uuid-> gets the hash value of the file name->integer.tohexstring ()
, use String.cahrat () to take out the directory name of the build directory, +root file path ("/web-inf/files/") mkdirs
6. Upload file size limit: Single File size limit
The entire request size limit
The parser has a related method: Sfu.setfilesizemax (100*1024); 100KB
Must be placed before parsing
If the limit is exceeded, an exception is thrown when parsing
Limit the entire form request size Sfu.setsizemax (); it is also performed before parsing
7. Cache Size and Temp directory
1. Cache size: Beyond how much to save to the hard drive, default 10KB
2. Save to what directory on the hard drive
diskfileitemfactory (int sizethreshold, File repository)
Using this constructor, you can specify the cache with the temp directory
2. Download: Download is the client response byte data
Requirements for download:
Two head a stream
Content-type (What type)
Content-dispositon (default is inline, browser can open he opens, picture, text, etc.)
To play the download box needs to be set to Accathment;filename=xxx
Stream is the file data to download
Download the details:
The Chinese name displayed in the Download box will appear garbled
Most mainstream browsers use URL encoding
General solution: FrameName = new String (Filename.getbytes (""), "");
A gadget class (here slightly) Filenameencoding method
Javaweb Basics-Upload in download