This time I will bring you the use of FormData to upload files through Ajax. What are theprecautions 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
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); } });
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
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.
"; } }; oReq.send(oData);
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
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); } }); }
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 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!