Home >Web Front-end >JS Tutorial >Using FormData to upload files with Ajax
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>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); } });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
JavaScriptto 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">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, 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>
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);
}
});
}
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 storageUse ajax to verify registered users Whether the name existsAjax operation form asynchronously uploads filesThe 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!