FormData
object, 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.
HTML code
<formID= "Uploadform"enctype= "Multipart/form-data">
<inputID= "File"type= "File"name= "File"/>
<ButtonID= "Upload"type= "button">Upload</Button>
</form>
JavaScript code
$.ajax ({
URL: '/upload ',
Type: ' POST ',
Cachefalse,
DataNewFormData ($ (' #uploadForm ') [0]),
ProcessData:false,
ContentType:false
}). Done (function(RES) {}). Fail (function(res) {});
Here are a few things to note:
processData
Set 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.
cache
Set to false
, the upload file does not need to be cached.
contentType
Set 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
?
FormData
uploading files using object add Field
HTML code
<DivID= "Uploadform">
<inputID= "File"type= "File"/>
<ButtonID= "Upload"type= "button">Upload</Button></Div> Not here.
<form>
Label, and there is no
enctype="multipart/form-data"
Property.
JavaScript code
varFormData =NewFormData ();
Formdata.append (' file ', $ (' #file ') [0].files[0]);
$.ajax ({
URL: '/upload ',
Type: ' POST ',
Cachefalse,
Data:formdata,
ProcessData:false,
ContentType: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]
.
contentType
Also 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.
Uploading files using Formdata objects via jquery Ajax