Uploading both data and files in one form using Ajax?

后端 未结 10 826
无人共我
无人共我 2020-11-21 05:48

I\'m using jQuery and Ajax for my forms to submit data and files but I\'m not sure how to send both data and files in one form?

I currently do almost the same with b

10条回答
  •  不知归路
    2020-11-21 06:41

    For me, it didn't work without enctype: 'multipart/form-data' field in the Ajax request. I hope it helps someone who is stuck in a similar problem.

    Even though the enctype was already set in the form attribute, for some reason, the Ajax request didn't automatically identify the enctype without explicit declaration (jQuery 3.3.1).

    // Tested, this works for me (jQuery 3.3.1)
    
    fileUploadForm.submit(function (e) {   
        e.preventDefault();
        $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                enctype: 'multipart/form-data',
                data: new FormData(this),
                processData: false,
                contentType: false,
                success: function (data) {
                    console.log('Thank God it worked!');
                }
            }
        );
    });
    
    // enctype field was set in the form but Ajax request didn't set it by default.
    
    
    ...

    As others mentioned above, please also pay special attention to the contentType and processData fields.

提交回复
热议问题