Reprinted from: http://www.cnblogs.com/labnizejuly/p/5588444.html
FormData
An object that can use a series of key-value pairs to simulate a complete form, and then XMLHttpRequest
send this "form" using .
Using the FormData object on the Mozilla Developer site has detailed object usage instructions.FormData
But in the upload file part, only the underlying XMLHttpRequest
object sends the upload request, so how to pass jQuery
the Ajax
upload?
This article will cover uploading files by jQuery
using objects.FormData
HTML code
< input id ="file" type ="file" name ="file" />
< button id ="upload" type ="button" > upload </ button >
</ form >
javascript code
url: '/upload',
type: 'POST',
cache: false ,
data: new FormData($('#uploadForm')[0]),
processData: false ,
contentType: false
}).done( function (res) { }).fail( function (res) {});
A few things to note here:
-
processData
set tofalse
. Becausedata
values areFormData
objects, no manipulation of the data is required. -
<form>
enctype="multipart/form-data"
Add attributes to tags . -
cache
Set tofalse
, upload files do not need to be cached. -
contentType
set tofalse
. Because it is<form>
an object constructed by a formFormData
and has declared propertiesenctype="multipart/form-data"
, it is set to false here.
After uploading, the server-side code needs to use the file
input stream object to get the file from the query parameter named as <input>
declared in name="file"
.
What if the object is not <form>
constructed with a form FormData
?
使用FormData
对象添加字段方式上传文件
HTML代码
< input id ="file" type ="file" />
< button id ="upload" type ="button" >upload </ button > </ div >
这里没有<form>
标签,也没有enctype="multipart/form-data"
属性。
javascript代码
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: '/upload',
type: 'POST',
cache: false ,
data: formData,
processData: false ,
contentType: false
}).done( function (res) { }).fail( function (res) {});
There are a few differences here:
-
append()
The second parameter of should be a file object, ie$('#file')[0].files[0]
. -
contentType
Also set to 'false'.
$('#file')[0].files[0]
You can see from the code that a <input type="file">
tag can upload multiple files,
just <input type="file">
add multiple
or multiple="multiple"
attribute in it.