Home >Web Front-end >JS Tutorial >Upload files through Ajax and use FormData to make Ajax requests

Upload files through Ajax and use FormData to make Ajax requests

亚连
亚连Original
2018-05-23 15:41:351519browse

This article mainly introduces the relevant information about uploading files through Ajax and using FormData to make Ajax requests. Friends in need can refer to the following

Uploading 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>

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 Request method:

Js code

$.ajax({ 
   url : "http://localhost:8080/STS/rest/user", 
   type : "POST", 
   data : $( &#39;#postForm&#39;).serialize(), 
   success : function(data) { 
     $( &#39;#serverResponse&#39;).html(data); 
   }, 
   error : function(data) { 
     $( &#39;#serverResponse&#39;).html(data.status + " : " + data.statusText + " : " + data.responseText); 
   } 
});

As above, the form can be serialized through $('#postForm').serialize(), thus All parameters in the form are passed 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.
But 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 usage

What 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 some key-value pairs to simulate a series of form controls through JavaScript. We can also use the send() method of XMLHttpRequest to do it 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 object, such as Chrome 7 , Firefox 4, IE 10, Opera 12, Safari 5.

See: https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/FormData

Here is only one way to initialize FormData through the form form

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

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);

See: https://developer.mozilla.org/zh-CN/docs/Web/Guide/Using_FormData_Objects

Use FormData to 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>

Js code

function doUpload() { 
   var formData = new FormData($( "#uploadForm" )[0]); 
   $.ajax({ 
     url: &#39;http://localhost:8080/cfJAX_RS/rest/file/upload&#39; , 
     type: &#39;POST&#39;, 
     data: formData, 
     async: false, 
     cache: false, 
     contentType: false, 
     processData: false, 
     success: function (returndata) { 
       alert(returndata); 
     }, 
     error: function (returndata) { 
       alert(returndata); 
     } 
   }); 
}

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to upload files using jQuery Ajax

Use ajax to implement asynchronous refresh requests

Ajax php realizes three-level linkage of product classification

The above is the detailed content of Upload files through Ajax and use FormData to make Ajax requests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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