Introduction to jQuery Ajax upload file processing method (recommended)

  After reading Blob, File, FileReader, and various transformation knowledge for a long time, I found that the way to upload files by Ajax is very simple.

  jQuery Ajax is very commonly used in web application development. It mainly includes ajax, get, post, load, getscript and other common non-refresh operation methods. Next, this article will introduce the jquery ajax upload file processing method.

   FormData object

  XMLHttpRequest Level 2 adds a new interface FormData. Using the FormData object, we can simulate a series of form controls with some key-value pairs through JavaScript, and we can also use the send() method of XMLHttpRequest to submit this form asynchronously ". Compared with normal 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+.

var formData = new FormData();
var name = $("input").val();
formData.append("file",$("#upload")[0].files[0]);
formData.append("name",name);
$.ajax({
url : Url,
type : 'POST',
data : formData,
// Tell jQuery not to process the sent data
processData : false,
// Tell jQuery not to set the Content-Type header
contentType : false,
beforeSend:function(){
console.log("In progress, please wait");
},
success : function(responseStr) {
if(responseStr.status===0){
console.log("成功"+responseStr);
}else{
console.log("failure");
}
},
error : function(responseStr) {
console.log("error");
}
});


Reprinted from: http://www.jb51.net/article/87654.htm

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326948610&siteId=291194637