multipart/formdata is not sending file data with jQuery.ajax

15,085

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

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

Share:
15,085
Zach Shallbetter
Author by

Zach Shallbetter

Updated on June 09, 2022

Comments

  • Zach Shallbetter
    Zach Shallbetter almost 2 years

    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.