Closed ardalis closed 1 year ago
@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
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 !
Any update on this? Do you know where I can find an example?