Submit a form to upload files through jQuery Ajax

 

 Reprinted from: http://www.cnblogs.com/labnizejuly/p/5588444.html

 

FormDataAn object that can use a series of key-value pairs to simulate a complete form, and then XMLHttpRequestsend 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 XMLHttpRequestobject sends the upload request, so how to pass jQuerythe Ajaxupload?
This article will cover uploading files by jQueryusing objects.FormData

 

HTML code 

< form  id ="uploadForm"  enctype ="multipart/form-data" >
     < input  id ="file"  type ="file"  name ="file" />
     < button  id ="upload"  type ="button" > upload </ button >
</ form >

 

javascript code 

copy code
$.ajax({
    url: '/upload',
    type: 'POST',
    cache:  false ,
    data:  new  FormData($('#uploadForm')[0]),
    processData:  false ,
    contentType:  false
}).done( function (res) { }).fail( function (res) {});  
copy code

 

 

 

 

A few things to note here:

 

  • processDataset to false. Because datavalues ​​are FormDataobjects, no manipulation of the data is required.
  • <form>enctype="multipart/form-data"Add attributes to tags .
  • cacheSet to false, upload files do not need to be cached.
  • contentTypeset to false. Because it is <form>an object constructed by a form FormDataand has declared properties enctype="multipart/form-data", it is set to false here.

After uploading, the server-side code needs to use the fileinput 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代码 

 

< div  id ="uploadForm" >
     < input  id ="file"  type ="file" />
     < button  id ="upload"  type ="button" >upload </ button > </ div >  

这里没有<form>标签,也没有enctype="multipart/form-data"属性。

 

javascript代码 

copy code
var  formData =  new  FormData();
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) {});  
copy code

 

There are a few differences here:

  • append()The second parameter of should be a file object, ie $('#file')[0].files[0].
  • contentTypeAlso 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 multipleor multiple="multiple"attribute in it.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326487890&siteId=291194637