File upload: ① before uploading (prepare a registered form page) Create a File upload control, click on the control to select the file that needs to be uploaded <form action= "/upload" method= "post" enctype= "Multip Art/form-data "> <input type=" file "name=" Headimg "/>Note: The upload type of the form must be: Multipart/form-dataThe upload method must be post when the Multipart/form-data is set, the characters are not encoded, and the values and data in the servlet must be encoded values, so to solve this problem, we need to encode the contents of the upload. ② prepare an uploaded servlet to the background to receive the normal form data and file (binary) ③ import the corresponding FileUpload jar package (Commons-fileupload-1.2.2.jar, Commons-io-1.4.jar). The role of these two packages, the former can let us through the tutorial learn the upload function of the file, the back of this package inside the
Filenameutils inside the tool can help us improve this file upload function fix bug
④ Open jar package with jar package to find index.html tips: There is always a development guide on the home page or Quick Start (quick starting) waiting for you ⑤ function code to complete a file upload based on QuickStart parsing: @WebServlet ("/ Upload ")
public class Uploadservlet extends HttpServlet {
@Override
protected void Service (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
Create a factory to parse this request, get a collection, this collection is a request object, encapsulated is each request data
try {
Create a factory
Fileitemfactory factory = new Diskfileitemfactory ();
Create a File Upload processor
Servletfileupload upload = new Servletfileupload (factory);
Parse this request: After parsing, we can get a collection of Fileitem.
List < fileitem > items = upload.parserequest (req);
By iterating through the collection you can get the property value of the uploaded file, including the property name, value.
for (Fileitem Fileitem:items) {
The above tests can look at the output, and the normal and file controls are treated differently.
if (Fileitem.isformfield ()) {
Representative is the general form, with the general form of the processing method to solve
}else{
Get the name of the uploaded file (with IE version issue)
String Upname=fileitem.getname ();
Problem with file upload with duplicate name
String upname = Filenameutils.getname (Fileitem.getname ());
There is a problem with saving path path some operating systems have no drive letter
File UploadFile = new file ("d:/", upname);
Write local files to the server
Fileitem.write (UploadFile);
}
}
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
} Description: This can only implement local upload, there are many bugs need to be repaired, there will be a detailed solution later
File Upload function implementation (i)