In fact, the file upload article has been written a lot, but a lot of articles are explained how to achieve, did not say this process in the end what happened (will not attract hatred.) , in fact, the implementation of file upload is not complicated, there is not much code, but if clearly understand the principle of this is still a bit of Kung fu, here on the restoration of the entire process of file upload.
In fact, the file upload in the earliest before the use of Apache Commons FileUpload components, but since the servlet proposed its own solution, no longer use this component, with the regular army who also use militia ah, no, not necessarily, Before the Apache HttpClient is more popular than JDK's own httpurlconnection, don't talk nonsense, go directly. first, the client programming below is our page fileupload.jsp
<%@ page language= "java" contenttype= "text/html" charset=iso-8859-1 "pageencoding=" %> <!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
There are several points to note about this page: first, the action is the URI, notice the difference between it and the URL, do not omit ContextPath, this will not find the resource; Enctype value must be multipart/form-data, This property refers to how the form data is encoded before it is sent to the server by assembling the form data into a single message and separating each part of the form with a delimiter; the default value is application/x-www-form-urlencoded, It also means that all values are encoded, this method is encoded using a key-value pair; If you want to upload multiple files, you can use the Multiple property, note that this property is proposed in the HTML5, so that we do not use multiple input to upload multiple files; below I upload three files, You can see the HTTP requests and responses as follows, I'm using the Chrome browser:
The most important side here is Content-type, which is the same type as the form enctype, and the most important is the addition of the boundary attribute, which is used to split the parts of the form. The following is the request payload issued on the Post form, as follows:
As you can see from the diagram, the entire uploaded form data is wrapped in delimiters and
Use the "separator--" method to indicate the end of the data, this delimiter must have the beginning and end of the data at the beginning and end, it appears in the middle only when there are multiple elements in the form, or multiple files are uploaded, and each delimited part contains the content-disposition header, which contains some attributes in the form element. There are name,filename, but the Content-type header is optional, and
There is no content-type part of the form's non-file, only the file domain will have content-type this header。 It is noteworthy that there will still be a file portion when no file is uploaded, except that the FileName property is empty, as follows:
second, the service-side programming Understanding the client is for us in the server to resolve the client sent over the request, then how to determine whether the request sent over to include the file. Based on the following points can be judged: in a request composed of Multipart/form-data, each part including the non-file part will be converted into a parts object, on the server side we are mainly to deal with it; Determine whether a part is a normal, content-type, or part of a file by looking for the presence of the header in the section, or if there is a content-type, then the file part exists, and then see if the file name that is uploaded is empty. The file name is empty to indicate that a client has not selected the file to upload, and if the file exists, use part's Write method to write him to the server-side file system, and the servlet to process file uploads on the server is as follows:
@WebServlet (name= "Fileuploadservlet", urlpatterns={"/fileuploadservlet"})//@MultipartConfig (location= "/") @ Multipartconfig public class Fileuploadservlet extends HttpServlet {private static final long Serialversionuid = 192042
3365061691218L;
@Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
collection<part> parts = Req.getparts ();
For (part Part:parts) {if (Part.getcontenttype ()!= null) {String filename = GetFileName (part);
if (filename!= null &&!filename.isempty ()) {part.write (filename);
}} String GetFileName (part part) {Objects.requirenonnull (part, ' part can ' null ');
String disposition = Part.getheader ("content-disposition");
string[] Disparts = Disposition.split (";");
String Filenamepart = disparts[disparts.length-1];
String filename = filenamepart.substring (filenamepart.indexof ("=") +1). Trim (). replace ("\", ""); Return FileName }
}About the above processing in fact mainly around the @multipartconfig annotation and part interface to carry out, about the use of these two is very simple, you can see Javadoc, but there are two I would like to focus on, because I have lost the pit: One is the location attribute in @multipartconfig, this is definitely a pit, when this value is an absolute path, it is no problem to call the part's write () method that writes the file to the corresponding path, but when it is relative to the path, as I wrote above. /"This relative path is relative to the C:\Program files\tomcat7\work\catalina\localhost\javaservlet path under the Tomcat path, which is a temporary saved location for a file upload, This path value is mainly to write to the hard disk when the file exceeds the preset size, so it is best not to use this property for @multisizethreshold, and another is that the GetName () method in part is not used to get the filename. Instead, it is used to get the name attribute in the form element; The filename needs to be parsed by ourselves; When using the Write () method of part, if the relative path is provided, then the root path of the relative path is C:\Program files\tomcat7\work\ Catalina\localhost\javaservlet;
Iii. Other issuesThe above two sections mainly explain how the client and the server are doing each other, but there are a number of other requirements that need to be considered in terms of specific business logic: Verifying and constraining file suffixes, constraining file sizes, storing files on a local file system or database, and coding problems with files. In particular, the coding problem in Chinese; avoid duplicate uploads of files of the same file name causing coverage problems; these problems are actually relatively simple to achieve, the following article can be used for reference, the main is afraid to consider these problems, or for easy to cut corners.