如何使用 jQuery.ajax 和 FormData 上传文件 [英] How to upload a file using jQuery.ajax and FormData
本文介绍了如何使用 jQuery.ajax 和 FormData 上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用 XMLHttpRequest 时,文件使用 FormData
.但是,当我切换到 jQuery.ajax
时,我的代码中断了.
When I use XMLHttpRequest, a file is correctly uploaded using FormData
. However, when I switch to jQuery.ajax
, my code breaks.
这是工作的原始代码:
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);
}
这是我失败的 jQuery.ajax
尝试:
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,
});
}
我做错了什么?如何使用 AJAX 正确上传文件?
What am I doing wrong? How can I get the file to be uploaded correctly, using AJAX?
推荐答案
您必须将 processData:false,contentType:false
添加到您的方法中,以便 jQuery 不会更改标题或数据(这会破坏您当前的代码).
You have to add processData:false,contentType:false
to your method, so that jQuery does not alter the headers or data (which breaks your current code).
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
}
});
}
这篇关于如何使用 jQuery.ajax 和 FormData 上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文