angularasp.net-core-webapi

How to send post request to upload multiple files from Angular to ASP.NET Core Web API?


This is my Angular service:

uploadFiles(formData: FormData) {
   const headerOptions = {
       headers: new HttpHeaders({
           'X-CSRF-TOKEN': token
       })
   };

   return this.httpClient
       .post<string>(`${this.configurationService.apiUrl}/cancellationforms/upload`, formData, headerOptions);
}
for (let file in this.supportDocuments) {
  // file is a blob object
  formData.append("files", file);
}

this.uploadService.uploadFiles(formData)

ASP.NET Core Web API endpoint:

routeBuilder.MapPost("api/cancellationforms/upload", ([FromForm] List<IFormFile> files, [FromServices] IServiceManager serviceManager, CancellationToken cancellationToken) =>
{
    return Results.Ok("Hello");
})
.WithName("CreateCancellationFormUpload")
.WithOpenApi();

The files from the endpoints are always null, if I use List. If I remove List, it will have the value of the latest blob object that I append in the UI.

Can anyone tell me what I am missing?

Thank you


Solution

  • You may try working with IFormFileCollection instead of List<IFormFile> type and without the [FromForm] attribute.

    routeBuilder.MapPost("api/cancellationforms/upload", 
        (IFormFileCollection files, 
        [FromServices] IServiceManager serviceManager, 
        CancellationToken cancellationToken) =>
    {
        // Iterate each file if needed
        foreach (IFormFile file in files)
        {
    
        }
    
        return Results.Ok("Hello");
    })