小编典典

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

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 }

任何帮助表示赞赏。


阅读 725

收藏
2020-07-26

共1个答案

小编典典

尝试:

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');
2020-07-26