如何上传使用jQuery.ajax和FORMDATA文件 [英] How to upload a file using jQuery.ajax and FormData
本文介绍了如何上传使用jQuery.ajax和FORMDATA文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用XMLHtt prequest,一个文件被正确地使用上传 FORMDATA
。然而,当我切换到 jQuery.ajax
,我的$ C $Ç休息。
When I use XMLHttpRequest, a file is correctly uploaded using FormData
. However, when I switch to jQuery.ajax
, my code breaks.
这是工作原来的code:
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);
}
下面是我的失败 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?
推荐答案
您必须添加过程数据:假的,则contentType:假
来你的方法,让jQuery的不改变头部或数据(它打破你目前的code)。
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屋!
查看全文