How to submit multipart formdata using jquery

2020-05-27 05:29发布

问题:

<form id="uploadForm" enctype="multipart/form-data" action="http://localhost:1337/ad/upload" method="post" name="uploadForm" novalidate>
    <input type="file" name="userPhoto" id="userPhoto" />
    <input type="submit" value="submit" id="uploadImage" />
</form>

This is my html form which accepts an image as file inout, the user can select an image file and then click submit. This works but the url of the current page changes to localhost:1337/ad/upload. I want the page to stay at the same url.

$("form#uploadForm").submit(function(event) {
    event.preventDefault();
    var formData = new FormData($(this)[0]);
    var posting = $.post(url, formData);

})

I have tried this to send the form using jquery but i get an error : Uncaught Type error : Illegal Invocation

What data does the form submit when the type is multipart /formdata and how can we get this data on jQuery

回答1:

processData

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

Please check jQuery Ajax Documentation

Try ajax like this -

var form = new FormData($("#uploadForm")[0]);
$.ajax({
        url: your_url,
        method: "POST",
        dataType: 'json',
        data: form,
        processData: false,
        contentType: false,
        success: function(result){},
        error: function(er){}
});


回答2:

You can give to the formData all form for processing

var form = $('#uploadForm')[0]; 
// You need to use standart javascript object here
var formData = new FormData(form);

or specify exact data for formdata

var formData = new FormData();
formData.append('userPhoto', $('input[type=file]')[0].files[0]);