I am using Aurelia Fetch Client to send a File Upload request to a Web API endpoint. But the IFormFile is empty all the tile. My code is below.
const formData = new FormData();
formData.append("files", account.statement);
const response = await this.http.fetch(url, { method: "POST", body: formData
});
[HttpPost]
public IActionResult Save ()
{
var files = Request.Form.Files;
}
files is always null. I have followed this post and have done as mentioned. But still cannot figure out what is wrong.
I figured out a way to do this using a DTO and specifying the uploaded file as a File object in FormData. This is because I had other field values that I needed to send with the File object.
Create DTO object with the required properties.
public class SaveAccountRequest
{
public string AccountName { get; set; }
public IFormFile Statement { get; set; }
}
Add the DTO as the accepted parameter in the controller endpoint.
[HttpPost]
public IActionResult SaveAccount([FromForm] SaveAccountRequest saveAccountRequest)
{
//you should be able to access the Statement property as an IFormFile in the saveAccountRequest.
}
Append all properties to the FormData object and make sure you name them according to the name used in the server-side DTO.
const formData = new FormData();
formData.append("accountName", accountName);
formData.append("statement", file);
Post the data to the SaveAccount endpoint. I am using the fetch API to post the data but a simple post should also work. Please make sure to set the content type to multipart form data when sending file requests.
this.http.fetch(<api endpoint url>, { method: "POST", body: formData, content-type: 'multipart/form-data' });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With