What is the correct way of posting form data with multiples files and the input field

22 Views Asked by At

I have an implementation for ajaxSubmit to post a form input data and multiple files to a backend as:

    var formData = new FormData();

    formData.append('pictureId', form.find("[name=pictureId]").val());
    formData.append('description', $('input[name=description]').val());
    formData.append('action', $('input[name=action]').val());


    for (var i = 0; i < filesToUpload.length; i++) {
        formData.append('file[]', filesToUpload[i]);
    }

    for (var pair of formData.entries()) {
        console.log(pair[0] + ', ' + pair[1]);
    }


    $("#frmPicture").ajaxSubmit({
        type: 'POST',
        dataType: 'html',
        cache: false,
        processData: false,
        data: formData, 
        success: function (responseText, statusText, xhr, el) {
            debugger;
            if (responseText == "") {
                $("#divAddPictureDialog").dialog("close");
                reloadPictures();
            }
            else {
                $("#spnPictureStatus").html(responseText);
            }
        }
    });

But this code gives me an error as:

Uncaught TypeError: Illegal invocation
    at init.$.fn.ajaxSubmit (jquery.form.js:97)
    at HTMLDivElement.savePicture (HotelDetails.aspx?id=61364:1576)
    at HTMLButtonElement.r.click (jquery-ui-1.10.1.custom.min.js:6)
    at HTMLButtonElement.dispatch (jquery-1.9.1.min.js:3)
    at HTMLButtonElement.v.handle (jquery-1.9.1.min.js:3)

After this I changed my code to data: {formData}, the form post happens. But i couldn't access the files on the server. The key file[] is never posted to the backend.

Can anyone suggest to me how to properly send the formdata using jquery.form.js.

0

There are 0 best solutions below