To upload a file, you need to use the Post method and set Enctype to Multipart/form-data.
<formAction= "/upload"Method= "POST"enctype= "Multipart/form-data"> <inputtype= "text"name= "param1"> <inputtype= "text"name= "Param2"> <inputtype= "File"name= "Fileparam"> <Buttontype= "Submit">Upload</Button></form>
About Multipart/form-data
Multipart/form-data is combined with the Post method, the Multipart/form-data POST request differs from the request header and the request body of the normal POST request.
The Content-type field value in the normal POST request header is:
content-type:application/x-www-form-urlencoded
Multipart/form-data the Content-type field value in the request header is multipart/form-data; Boundary=xxxxxxx, (xxxxxx specifies the content delimiter in the request body).
Content-type:multipart/form-data; boundary=----WEBKITFORMBOUNDARYZPSWTSOIRHI0TBW7
The request for a normal post request is in a physical style (does not upload the file contents):
param1=aaaa¶m2=123456&fileparam=test.txt
The Multipart/form-data request is a physical type (containing the file contents):
------webkitformboundaryjuvxj3psltebh9ascontent-disposition:form-data; Name="param1"AAAA------webkitformboundaryjuvxj3psltebh9ascontent-disposition:form-data; Name="Param2"123456------webkitformboundaryjuvxj3psltebh9ascontent-disposition:form-data; Name="Fileparam"; Filename="Test.txt"Content-type:text/plaincontents offile------Webkitformboundaryjuvxj3psltebh9as
Background processing
Data submitted using Multipart/form-data cannot be read using methods such as the GetParameter () of the HttpServletRequest object. You can read the entire request body data stream itself to parse the data. But the better way is to use the already existing third-party tool classes, such as Fileupload,jspsmartupload. In the following example, FileUpload is used.
Httpservletrequeest request=.... Servletfileupload.ismultipartcontent (Request))
{Fileitemfactory Factory=Newdiskfileitemfactory (); Servletfileupload Upload=Newservletfileupload (Factory); List<FileItem> items =upload.parserequest (Request); for(Fileitem i:items) {i.getfieldname (); //Name of parameter//i.getstring (); //parameter value (return string), or file content if the file is uploaded//I.get (); //parameter value (returns a byte array), or the file content if the file is uploaded
I.getsize (); The byte size of the parameter value//I.getname (); //file name for uploading files //I.getcontenttype (); //content Type of uploaded file if(!i.isformfield () &&i.getsize () >0)//Simple parameter returns True, File returns falseFiles.write (Paths.get ("/upload/" +Paths.get (I.getname ()). GetFileName ()), I.get ()); }
}
Multipart/form-data Request and File upload