FormDataobject, you can use a series of key-value pairs to simulate a complete form, and then use the XMLHttpRequest "form" to send it.
Use the Formdata object on the Mozilla Developer website for detailed FormData object usage instructions.
But the upload file part only the bottom XMLHttpRequest object sends the upload request, then how jQuery to pass the Ajax upload?
This article describes jQuery FormData uploading files by using objects.
Use
<form>Form initialization
FormDataObject Mode upload File
HTML code
<formID= "Uploadform"enctype= "Multipart/form-data"> <inputID= "File"type= "File"name= "File"/> <ButtonID= "Upload"type= "button">Upload</Button></form>
JavaScript code
$.ajax ({ '/upload ', ' POST ', false, new FormData ($ (' #uploadForm ') [0]), false, false}). Done ( function(res) {}). Fail (function(res) {});
Here are a few things to note:
processDataSet to false . Because the data value is an FormData object, you do not need to process the data.
<form>tag to add a enctype="multipart/form-data" property.
cacheSet to false , the upload file does not need to be cached.
contentTypeSet to false . This is set to false because it is an <form> object constructed by a form, and the FormData property has already been declared enctype="multipart/form-data" .
After uploading, the server-side code needs to use the file get file input stream object from the query parameter name, because <input> it is declared in name="file" .
<form>What if I didn't construct the object with a form FormData ?
Use
FormDataObject add field mode upload file
HTML code
<DivID= "Uploadform"> <inputID= "File"type= "File"/> <ButtonID= "Upload"type= "button">Upload</Button></Div>
There are no <form> tags and no enctype="multipart/form-data" attributes.
JavaScript code
var New FormData (); Formdata.append (' file ', $ (' #file ') [0].files[0]); $.ajax ({ '/upload '), ' POST ', false, data:formdata, false, false}). Done (function(res) {}). Fail (function(res) { });
Here are a few places that are different:
append()The second parameter should be a file object, that is $(‘#file‘)[0].files[0] .
contentTypeAlso set to ' false '.
From the code $(‘#file‘)[0].files[0] you can see <input type="file"> that a tag can upload multiple files,
You only need to <input type="file"> add multiple or multiple="multiple" attribute in.
Server-side Read file
From the Servlet 3.0 beginning, request.getPart() the uploaded file can be obtained via or request.getPars() two interfaces.
Uploading files using Formdata objects via jquery Ajax