Home > front end >  How to upload file outside or controller and not in IFormFile type
How to upload file outside or controller and not in IFormFile type

Time:12-29

I use Mediatr for handling commands and queries in Application project which were sent from WebApi project. In WebApi project user sends to controller IFormFile. To handle IFormFile in Application project I have to install aspnetcore.http.features. But I do not want this dependency in Application project. How can I send user file not in IFormFile to handler of Application project from controller?

CodePudding user response:

You can read the contents of the file into a byte array and pass the byte array as a parameter to your Mediatr request.

[HttpPost]
public async Task<IActionResult> Post([FromForm]IFormFile file)
{
    using (var stream = new MemoryStream())
    {
        await file.CopyToAsync(stream);
        var fileContents = stream.ToArray();

        var result = await _mediator.Send(new YourMediatrRequest(fileContents));

        return Ok(result);
    }
}


public class YourMediatrRequestHandler : IRequestHandler<YourMediatrRequest, YourMediatrResponse>
{
    public Task<YourMediatrResponse> Handle(YourMediatrRequest request, CancellationToken cancellationToken)
    {
        var fileContents = request.FileContents;
        ...more code
    }
}
  • Related