通过 ajax 发送 FormData 对象和附加参数

Send FormData object AND an additional parameter via ajax

我已经成功发送了一个 FormData 对象,如下所示:

var formData = new FormData();
formData.append('file', this.files[0]);
$.ajax({
   url: urlUploadProductsFile,
   type: 'POST',
   data: formData,
   cache: false,
   contentType: false,
   processData: false
}, 'json');

现在我要做的是添加一个额外的 CustomerId 发送到服务器。以下将不起作用:

var formData = new FormData();
formData.append('file', this.files[0]);
$.ajax({
   url: urlUploadProductsFile,
   type: 'POST',
   data: { "file": formData, "CustomerId": 2 },
   cache: false,
   contentType: false,
   processData: false
}, 'json');

我还尝试了以下变体:

data: { "file": formData, "CustomerId": 2 }, processData: true

data: JSON.stringify({ "file": formData, "CustomerId": 2 })

data: { "file": JSON.stringify(formData), "CustomerId": 2 }

data: { file: formData, CustomerId: 2 }

感谢任何帮助。

您需要将其直接添加到 formData(就像您对 'file' 所做的那样),或者使用查询 (GET) 参数。

尝试:

var formData = new FormData();
formData.append('file', this.files[0]);
formData.append('CustomerId', 2);

/*
 note:: appending in form Data will give "csrf token mismatch error". 
 so better you make a input feild of type hidden with name = CustomerId 
 and value =  2 
*/ 

$.ajax({
   url: urlUploadProductsFile,
   type: 'POST',
   data: formData,
   cache: false,
   contentType: false,
   processData: false
}, 'json');