qwaz
qwaz

Reputation: 1305

upload file via Ajax appending data with append() not working

When I upload file to external server via Ajax call passing form data to FormData(); via hidden input fields of the submitted form, everything works fine.

However, when I'm passing form data to FormData(); by appending it to FormData();, it does not work.

How come that the processing of the data is somehow different when you pass data via hidden fields from when you append data. Since in the second case it doesn't work.

This method works:

$('#myform').on('submit', function(e){
    var formdata = new FormData(this);
    $.ajax({
        url: 'https://external-website.com/',
        type: 'POST',
        data: formdata,
        processData: false,
        contentType: false
    });
});

<form id="myform" method="post" enctype="multipart/form-data">
    <input type="hidden" name="key1" value="value1">
    <input type="hidden" name="key2" value="value2">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>

This method does not work:

$('#myform').on('submit', function(e){
    var formdata = new FormData(this);
    formdata.append('key1', 'value1');
    formdata.append('key2', 'value2');
    $.ajax({
        url: 'https://external-website.com/',
        type: 'POST',
        data: formdata,
        processData: false,
        contentType: false
    });
});


<form id="myform" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>

Upvotes: 0

Views: 1470

Answers (2)

Adeniyi Shalom
Adeniyi Shalom

Reputation: 1

let formdata = new FormData;
formdata.append('file', $(YourElement).files[0]);

I think files is an array that can be accessed when [0] is placed in front of it.

Upvotes: 0

Denis Shulepov
Denis Shulepov

Reputation: 381

I don't see you calling e.preventDefault(); in form submit handler which means your form is also submitted the usual way (in addition to an ajax request you send). This might be the case why it works in a first example - you have all the fields in a form and it's submitted. Check out the network tab in dev tools to see how may requests are done and if your page is reloaded. Also trace on server how many requests are received and with what parameters.

Upvotes: 1

Related Questions