61

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?

0

2 Answers 2

173

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
       }
    });
}  
Sign up to request clarification or add additional context in comments.

18 Comments

I'd upvote this 1000 times if i could. Out of all the other answers to this question on SO, this one worked the best and is the simplest. thanks.
Warning: FormData is not supported in IE until version 10.
In this answer (and question), what is blobFile? Is it an input.val()?
@tmyie It is a Blob or File object, e.g. for <input type="file" id="filechooser"> it is document.getElementById('filechooser').files[0] (provided that the user has selected a file). (in jQuery, $('#filechooser')[0].files[0])
@MarceloBarbosa fd.append('field_name', 'string_field_value'); - see developer.mozilla.org/en-US/docs/Web/API/FormData
|
0

If you are uploading from a HTML5 form that includes an input fo type file you can just use querySelector and FormData and it works.

In case of php it will give you all files in the $_FILE and all other inputs in the $_POST array.

JS/jQuery:

function safeFormWithFile()
{
  var fd = new FormData(document.querySelector('#myFormName'));

  $.ajax({
        url:'/catchFormData.php',
        method:'POST',
        data:fd,
        processData: false,
        contentType: false,
        success:function(data){
          console.log(data);
        }
  });
}

HTML:

<form id="myFormName">
  <input id="myImage" name="myImage" type="file">
  <input id="myCaption" name="myCaption" type="text">
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.