Home > Web Front-end > JS Tutorial > Using FormData to upload files with Ajax

Using FormData to upload files with Ajax

php中世界最好的语言
Release: 2018-04-03 17:27:57
Original
1710 people have browsed it

This time I will bring you the use of FormData to upload files through Ajax. What are the precautions for using FormData to upload files through Ajax? The following is a practical case, let's take a look.

Upload files through traditional form submission:

Html code

<form id= "uploadForm" action= "http://localhost:8080/cfJAX_RS/rest/file/upload" method= "post" enctype ="multipart/form-data"> 
   <h1 >测试通过Rest接口上传文件 </h1> 
   <p >指定文件名: <input type ="text" name="filename" /></p> 
   <p >上传文件: <input type ="file" name="file" /></p> 
   <p >关键字1: <input type ="text" name="keyword" /></p> 
   <p >关键字2: <input type ="text" name="keyword" /></p> 
   <p >关键字3: <input type ="text" name="keyword" /></p> 
   <input type ="submit" value="上传"/> 
</form>
Copy after login
However, traditional form submission will cause the page to refresh, but In some cases, we do not want the page to be refreshed. In this case, we all use Ajax to make requests:

Js code

$.ajax({ 
   url : "http://localhost:8080/STS/rest/user", 
   type : "POST", 
   data : $( '#postForm').serialize(), 
   success : function(data) { 
     $( '#serverResponse').html(data); 
   }, 
   error : function(data) { 
     $( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText); 
   } 
});
Copy after login
As above, through $('#postForm').serialize() can serialize the form, thereby passing all parameters in the form to the server.

However, in the above method, only general parameters can be passed, and the file stream of the uploaded file cannot be serialized and passed.

However, now mainstream browsers have begun to support an object called FormData. With this FormData, we can easily use Ajax to upload files
.

About FormData and its usageWhat is FormData? Let's take a look at the introduction on Mozilla.

XMLHttpRequest Level 2 adds a new interface FormData. Using the FormData object, we can use

JavaScript

to simulate a series of form controls with some key-value pairs. We can also use XMLHttpRequest's send () method to asynchronously submit this "form". Compared with ordinary ajax, the biggest advantage of using FormData is that we can upload a binary file asynchronously. Newer versions of all major browsers already support this Objects, such as Chrome 7+, Firefox 4+, IE 10+, Opera 12+, Safari 5+.

See:

https://

developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/FormDataOnly one form passed from is shown here How to initialize FormData

<form enctype="multipart/form-data" method="post" name="fileinfo">
Copy after login

Js code

var oData = new FormData(document.forms.namedItem("fileinfo" )); 
oData.append( "CustomField", "This is some extra data" ); 
var oReq = new XMLHttpRequest(); 
oReq.open( "POST", "stash.php" , true ); 
oReq.onload = function(oEvent) { 
   if (oReq.status == 200) { 
     oOutput.innerHTML = "Uploaded!" ; 
   } else { 
     oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>"; 
   } 
}; 
oReq.send(oData);
Copy after login
See: https://developer.mozilla.org/zh-CN/docs/Web/Guide/Using_FormData_Objects

Use FormData, make Ajax requests and upload files

JQuery is used here, but older versions of JQuery such as 1.2 are not supported. It is best to use 2.0 or newer versions:

Html code

<form id= "uploadForm"> 
   <p >指定文件名: <input type="text" name="filename" value= ""/></p > 
   <p >上传文件: <input type="file" name="file"/></ p> 
   <input type="button" value="上传" onclick="doUpload()" /> 
</form>
Copy after login

Js code

function doUpload() { 
   var formData = new FormData($( "#uploadForm" )[0]); 
   $.ajax({ 
     url: 'http://localhost:8080/cfJAX_RS/rest/file/upload' , 
     type: 'POST', 
     data: formData, 
     async: false, 
     cache: false, 
     contentType: false, 
     processData: false, 
     success: function (returndata) { 
       alert(returndata); 
     }, 
     error: function (returndata) { 
       alert(returndata); 
     } 
   }); 
}
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to php Chinese website Other related articles!

Recommended reading:

js+ajaxcap operates the json object and loops it to the table for storage


Use ajax to verify registered users Whether the name exists


Ajax operation form asynchronously uploads files

The above is the detailed content of Using FormData to upload files with Ajax. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template