使用FormData上传JQuery / AJAX文件,文件不发布[重复]

时间:2022-04-23 03:20:28

This question already has an answer here:

这个问题在这里已有答案:

This works when submitting the form directly. Perhaps I am not passing my "form" object to FormData correctly. Laravel is saying that "file" isn't being passed and when I console.log(formData), I'm seeing an object containing the proto prop but as far as I can tell none of my fields

这在直接提交表单时有效。也许我没有正确地将我的“表单”对象传递给FormData。 Laravel说“文件”没有传递,当我在console.log(formData)时,我看到一个包含原型道具的对象,但据我所知,我的字段都没有

HTML

HTML

<form enctype="multipart/form-data" accept-charset="utf-8" method="POST" action="/file">
<input id="file" type="file" name="file">
<button type="submit">Upload</button>
</form>

JS

JS

$('.file-upload-form').submit(function (e) {
    e.preventDefault();
    submitUploadFileForm($(this)); //also tried just passing this without wrapper
});
function submitUploadFileForm(form){
    console.log(form);
    var formData = new FormData(form); //Needed for passing file
    console.log(formData);
    $.ajax({
        type: 'post',
        url: '/file',
        data: formData,
        success: function () {
            alert('done');
        },
        processData: false,
        contentType: false
    });
}

1 个解决方案

#1


4  

FormData accepts a form DOMElement, not a jQuery object. You need to call submitUploadFileForm() just passing the this reference to the form:

FormData接受表单DOMElement,而不是jQuery对象。您需要调用submitUploadFileForm(),只需将此引用传递给表单:

submitUploadFileForm(this);

#1


4  

FormData accepts a form DOMElement, not a jQuery object. You need to call submitUploadFileForm() just passing the this reference to the form:

FormData接受表单DOMElement,而不是jQuery对象。您需要调用submitUploadFileForm(),只需将此引用传递给表单:

submitUploadFileForm(this);