jQuery AJAX 'multipart/form-data' 不发送数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12831680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:03:01  来源:igfitidea点击:

jQuery AJAX 'multipart/form-data' Not Sending Data?

ajaxjqueryfile-uploadmultipartform-data

提问by Julian

I'm at a loss for why I can't get jQuery to pass upload data seeing as the AJAX object appears to be configured correctly, and the correct Content-Type/MIME-Type headers are being sent.

我不知道为什么我无法让 jQuery 传递上传数据,因为 AJAX 对象似乎配置正确,并且正在发送正确的 Content-Type/MIME-Type 标头。

I've tried two separate forms of request--one with a FormData object contained within a literal, and also just passing the FormData object directly.

我尝试了两种不同的请求形式——一种是包含在文字中的 FormData 对象,另一种是直接传递 FormData 对象。

Unfortunately either way I can't get anything to pass, and both $_FILES and $_POST are empty arrays.

不幸的是,无论哪种方式我都无法传递任何东西,并且 $_FILES 和 $_POST 都是空数组。

The ideal request I wish to use is as follows:

我希望使用的理想请求如下:

enter image description here

在此处输入图片说明

Along with the following code:

连同以下代码:

var files = new FormData();

$.each(context.prototype.fileData, function(i, obj) { files.append(i, obj.value.files[0]); });

var request = { action: 'upload', id: response.obj.id, data: files };

$.ajax({

    type        : 'POST',
    url         : context.controller,
    data        : request,
    processData : false,
    contentType : 'multipart/form-data',
    mimeType    : 'multipart/form-data',

    success     : function(r) {
        console.log(r);
        //if (errors != null) { } else context.close();

    },

    error       : function(r) { alert('jQuery Error'); }

});

Once again the only response (looking at both the Network tab & Console) when I try to export both $_FILES and $_POST is simply two empty arrays...

再次尝试导出 $_FILES 和 $_POST 时唯一的响应(同时查看网络选项卡和控制台)只是两个空数组...

回答by Musa

You have to pass the FormDataobject as the data parameter

您必须将FormData对象作为数据参数传递

var request = new FormData();                   
$.each(context.prototype.fileData, function(i, obj) { request.append(i, obj.value.files[0]); });    
request.append('action', 'upload');
request.append('id', response.obj.id);
$.ajax({

    type        : 'POST',
    url     : context.controller,
    data        : request,
    processData : false,
    contentType : false,                        
    success     : function(r) {
        console.log(r);
        //if (errors != null) { } else context.close();

    },

    error       : function(r) { alert('jQuery Error'); }

});