26

I have managed to send a FormData object like so:

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

Now what I want to do is add an additional CustomerId to send to the server. The following won't work:

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');

And I also tried the following variations:

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 }

Any help appreciated.

iuliu.net
  • 6,666
  • 6
  • 46
  • 69

2 Answers2

39

Try:

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');
Aditya Tomar
  • 841
  • 1
  • 13
  • 20
Borik Bobrujskov
  • 823
  • 1
  • 7
  • 11
  • what if the secondary data was not a simple type like 2? What if I also needed to send a json object? How would I encode it in the front end, and how would I unencode it in the controller? – Joe Feb 21 '19 at 20:02
  • JSON is a simple string. You can escape it as pointed there: https://www.freeformatter.com/json-escape.html > The following characters are reserved in JSON and must be properly escaped to be used in strings: Backspace is replaced with \b Form feed is replaced with \f Newline is replaced with \n Carriage return is replaced with \r Tab is replaced with \t Double quote is replaced with \" Backslash is replaced with \\ – Borik Bobrujskov Feb 21 '19 at 20:08
  • For anyone coming here in the future, the extra parameters I added were put in the `params` object of `req` (request). – NetOperator Wibby Aug 17 '19 at 15:49
2

You need to either add it directly to formData (just as you did with 'file'), or alternatively use query (GET) parameters.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43