如何将对象传递给包含文件对象的formdata

时间:2014-05-27 03:45:23

标签: javascript php ajax multipartform-data form-data

我想将以下类型的数据传递给webservice

travelData = {
    "method": "add_edit_request",
    "params": {
        "request_by": requestOf,
        "purpose_of": travelPurpose,                            
        "filename":file_data
    }
};

其中file_data为$("#fileInput").prop("files")[0];

我想使用FormData传递文件。

我已经使用formData

完成了以下代码传递数据
var formdata = new FormData();
formdata.append("method","add_edit_travel_request");

parameters={};
parameters["request_by"]=requestOf;
parameters["purpose_of_travel"]=travelPurpose;
parameters["filename"]=file_data;
formdata.append("params",JSON.stringify(parameters));

我有以下类型的ajax调用

return $.ajax({
            url: url,
            method: 'POST',
            data: data,
            dataType:type,
            cache: false,
            crossDomain: true,
            contentType : false,
            processData: false,
            success: function(data) {
                console.log(data);

                var args = arguments[2];
                callback.call(this, data, args.statusText, args);
            },
            fail: function(data) {

                xhrServerObj = xhr;
                errorcallback.call(xhr, ajaxOptions, thrownError);
            }
});

并将其称为

Utils.Ajax.uploadFile(Utils.WebAPI.WebAPIServer,formdata , this.RequestCallBack, 'json', this.RequestFailureCallBack);

1 个答案:

答案 0 :(得分:0)

要将对象包含文件对象传递给FormData,请尝试使用Object.entries()

// If this is the object you want to convert to FormData...
const item = {
    description: 'First item',
    price: 13,
    photo: File
};

const formData = new FormData();

Object.entries(item).forEach(([key, value]) => {
    formData.append(key, value);
});

// At this point, you can then pass formData to your handler method

在此处详细了解有关Object.entries()的信息-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries