ardalis/ApiEndpoints

Docs: Add a sample showing how to do a file upload

ardalis opened this issue · 7 comments

Docs: Add a sample showing how to do a file upload

Any update on this? Do you know where I can find an example?

@jonathanjameswilliams26 did you manage to find a way to do the file upload?

@belavenuto Yeah I was able to use the [FromForm] attribute on my request dto.

public record UploadFileRequest
{
      [FromForm]
      public IFormFile File { get; set; }
}

And this is what I had to use in postman
image

Not worked to me ...someone can help me ?

@renannn it worked for me. This is my endpoint:

public class PurchaseOrderReadXml : EndpointBaseAsync .WithRequest<PurchaseOrderUploadXmlRequest> .WithActionResult<PurchaseOrderDto>

The handle method:

public override async Task<ActionResult<PurchaseOrderDto>> HandleAsync( [FromForm] PurchaseOrderUploadXmlRequest request, CancellationToken cancellationToken) {

The DTO:

public class PurchaseOrderUploadXmlRequest { [FromForm] public IFormFile? File { get; set; } }

Why would it work any differently than on a normal controller?

Using the sample, for example:

using Ardalis.ApiEndpoints;
using Microsoft.AspNetCore.Mvc;

namespace SampleEndpointApp.Endpoints.Authors;

public class File : EndpointBaseAsync
    .WithRequest<IFormFile>
    .WithResult<ActionResult<string[]>>
{
  /// <summary>
  /// Post author's photo or something
  /// </summary>
  [HttpPost("api/[namespace]/file")]
  public override async Task<ActionResult<string[]>> HandleAsync(
    IFormFile file,
    CancellationToken cancellationToken = default)
  {
    string filePath = Path.GetTempFileName();
    using (var fileStream = System.IO.File.Create(filePath))
    {
      await file.CopyToAsync(fileStream, cancellationToken);
    }

    return new[]
    {
      filePath,
      file.FileName,
      file.ContentType,
      file.ContentDisposition,
      file.Length.ToString()
    };
  }
}

Works OK with Swagger and Postman.

Model binding docs: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-7.0.

File upload docs (read this if you want streaming instead of buffering): https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-7.0.

Thanks @mariusz96 !