0

I currently upload a file to my controller and it works fine:

On the client side:

var input = document.getElementById(inputId);
var formData = new FormData();
for (var i = 0; i != input.files.length; i++) {
  formData.append("files", files[i]);
}    

$.ajax({
  url: "/api/ocr",
  data: formData,
  processData: false,
  contentType: false,
  type: "POST",
  success: function(data) {...}
});

On the server side in the controller:

[HttpPost]
public async Task<IActionResult> Post(IList<IFormFile> files) {
  IFormFile file = files[0];
  // process file
}

Now I want to send another parameter to server: connectionId. So on the client side I added:

formData.append("connectionId", "123456");

and on the serverside, I amended the parameter to the Post method:

[HttpPost]
public async Task<IActionResult> Post(IList<IFormFile> files, string connectionId) {
  ...
}

However, connectionId parameter is always null. What am I missing?

AngryHacker
  • 59,598
  • 102
  • 325
  • 594

1 Answers1

0

Check that your Form element contains:

<form enctype="multipart/form-data" method="post">

and try passing the Form element into the FormData constructor:

var formData = new FormData(document.getElementById(formId));

If your Model Binding is case sensitive, make sure the id is too:

<input type="text" id="connectionId"

and also that the connectionId input is being populated in the DOM before clicking submit using the browser's dev tools.

  • There is no form on the page. Everything is being called via ajax, thus `$.ajax` – AngryHacker Aug 12 '21 at 05:07
  • @AngryHacker it doesn't matter, you can still send `multipart/form-data` requests with `$.ajax`. https://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax – abdusco Aug 12 '21 at 08:47