How to upload a file using jQuery.ajax and FormData
When I use XMLHttpRequest, a file is correctly uploaded using FormData
. However, when I switch to jQuery.ajax
, my code breaks.
This is the working original code:
function uploadFile(blobFile, fileName) {
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php", true);
xhr.send(fd);
}
Here is my unsuccessful jQuery.ajax
attempt:
function uploadFile(blobFile, fileName) {
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xm = $.ajax({
url: "upload.php",
type: "POST",
data: fd,
});
}
What am I doing wrong? How can I get the file to be uploaded correctly, using AJAX?
你必须为你的方法添加processData:false,contentType:false
,这样jQuery不会改变头文件或数据(这会破坏你当前的代码)。
function uploadFile(blobFile, fileName) {
var fd = new FormData();
fd.append("fileToUpload", blobFile);
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
// .. do something
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
}
链接地址: http://www.djcxy.com/p/55776.html