ardalis / ApiEndpoints

A project for supporting API Endpoints in ASP.NET Core web applications.
MIT License
3.13k stars 227 forks source link

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

Closed ardalis closed 1 year ago

jonowilliams26 commented 2 years ago

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

belavenuto commented 2 years ago

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

jonowilliams26 commented 2 years ago

@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

renannn commented 2 years ago

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

belavenuto commented 2 years ago

@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; } }

mariusz96 commented 1 year ago

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.

ardalis commented 1 year ago

Thanks @mariusz96 !