0

I am trying to send a .png image from the client to a .NET Core API. I am following the official .NET Core documentation exactly in the API, so my controller endpoint looks like this:

[HttpPut]
public async Task<IActionResult> SaveFile(List<IFormFile> files) {...}

Since I am using Axios, I am using the following example for the front end code:

axios.put(url, imageFile, {
  headers: {
    'Content-Type': imageFile.type
  }
});

I have also tried wrapping the image file into the FormData class like so:

const formData = new FormData(driversLicenseFile);
axios.put(url, formData , {...

What am I doing wrong? How do I avoid the 415 response code?

The request, the way it appears in the browser is included below, in case that helps you spot any obvious issues.

enter image description here

VSO
  • 11,546
  • 25
  • 99
  • 187

1 Answers1

1

When I do stuff like this, I think, how would ASP.NET Core know how to bind imageFile to a List<IFormFile> files.

You need to use FormData and you should append with a name that matches the name of parameter for your action, i.e. files.

Quick Demo

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script type="text/javascript">
function upload(ev) {
    let file = document.getElementById("file-upload").files[0];
    let fd = new FormData();
    fd.append("files", file);

    axios.put(url, fd);
}
</script>

<input id="file-upload" type="file" oninput="upload()" />
Shoejep
  • 4,414
  • 4
  • 22
  • 26
  • Changing `const formData = new FormData(driversLicenseFile);` to `const formData = new FormData();` and then `formData.append("files", driversLicenseFile);` was all it took. Didn't need to change the UI. Didn't need to upload immediately `oninput`. Thank you very much for you help! Like you said, `files` for the name of the file, had to match the name of the argument in `.NET Core`. – VSO Sep 17 '20 at 20:49
  • 1
    Glad it worked. Only included `oninput="upload()"` as part of the demo. – Shoejep Sep 17 '20 at 20:52
  • I am only clarifying that I didn't need it because almost every example I have found requires an immediate form submission. That had me thinking that it may be REQUIRED to submit immediately, just mentioning it so other people reading this question avoid the same confusion I had (which you didn't cause). Your answer is great. – VSO Sep 17 '20 at 20:55