7

I have an endpoint from our Django backend guys with documentation that reads:

POST to /api/1/photo-uploads/ with enctype="multipart/form-data" with files in field called "files[]".

I've been attempting to send uploaded files with formData using jquery's AJAX method. I continue to get an error indicating that the file was not sent. When I view the payload I see.

undefined
------WebKitFormBoundary9AzM2HQPcyWLAgyR
Content-Disposition: form-data; name="file"; filename="auzLyrW.jpg"
Content-Type: image/jpeg

Which doesn't necessarily mean that it hasn't sent but there certainly isn't a location being posted. And I don't have any kind of verification that the file is uploaded.

    var formData = new FormData();
    formData.append('file', $('#file-upload').get(0).files[0]);
    $.ajax({
        url: '/api/1/photo-uploads/',
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
    });

When I console.log formData it simply show's the prototype methods like .append. So I'm unable to verify if the file's data is being sent beyond checking the payload. I can log $('#file-upload').get(0).files[0] but I only see details from the file itself. Because I'm testing it locally an upload location should be something like localhost:8000/.

The backend guys are under the impression that it's something I'm doing. When I do a simple form post it works fine. I've tried a number of plugins and basic methods and all have produced the 400 {"message": "No photos supplied.", "success": false}

Any ideas would be appreciated.

Zach Shallbetter
  • 1,901
  • 6
  • 23
  • 37
  • 1
    Have you looked at http://stackoverflow.com/questions/9622901/how-to-upload-a-file-using-jquery-ajax-and-formdata and http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery – Rohan Dec 20 '13 at 05:21
  • @Rohan yeah my code above is an amalgam of those two answers. Unless I missed something. – Zach Shallbetter Dec 20 '13 at 05:25
  • I also wanted to call out this well documented question. It didn't solve my issue but it was well done http://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery – Zach Shallbetter Dec 20 '13 at 06:09

1 Answers1

7

The documentation asked that it be called files[]. What was being sent was file.

formData.append('files[]', $('#file-upload').get(0).files[0]);

Zach Shallbetter
  • 1,901
  • 6
  • 23
  • 37