Crisiiii
Crisiiii

Reputation: 409

Send file by Ajax and FormData fail

I'm trying to send a file using Ajax in Jquery creating a FormData previously. This is my code:

var inputFileImage = document.getElementById('uploadImage');
var file = inputFileImage.files[0];
var data = new FormData();                  
data.append('archivo',file);

jQuery.ajax({
    url: '/services/rpc.php',
    type: 'post',
    data: {functionName: 'saveProfileImage', data : data},
    contentType:false,
    processData:false,
})
.done(function(response) {
    alert(response);            
}.bind(this))
.fail(function(response) {
     alert('Sorry, there was an unexpected error, please try again later.\n\nInformation about the error:\n'+response);
        });

This ajax always goes to the fail function, and if I change the processData to true returns my another error saying Error: TypeError: 'append' called on an object that does not implement interface FormData.

Thanks for your help!

Upvotes: 0

Views: 935

Answers (1)

Mr.Manhattan
Mr.Manhattan

Reputation: 5504

processData has to be off to send binary data. The FormData element is completely used as binary data, while data:{} needs to be processed. Additional parameters have to be appended to the formData in this case!

var data = new FormData();                  
data.append('archivo',file);               
data.append('functionName','saveProfileImage');

jQuery.ajax({
    url: '/services/rpc.php',
    type: 'post',
    data: data,
    contentType:false,
    processData:false,
});

Upvotes: 2

Related Questions