Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  28] [ 2]  / answers: 1 / hits: 89226  / 12 Years ago, thu, march 8, 2012, 12:00:00

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?


More From » jquery

 Answers
-6

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
}
});
}

[#86975] Wednesday, March 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;