Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Web API IFormFile Empty, When sending FormData request

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.

Client Side

const formData = new FormData();
formData.append("files", account.statement);

const response = await this.http.fetch(url, { method: "POST", body: formData 
});

Web API End Point

[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.

like image 305
Priyan Perera Avatar asked Oct 17 '22 12:10

Priyan Perera


1 Answers

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.

Server

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.
}

Client

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' });
like image 57
Priyan Perera Avatar answered Oct 20 '22 22:10

Priyan Perera