Search code examples
c#asp.net-corefile-uploadcqrsmediatr

How to upload file outside of controller and not in IFormFile type


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


Solution

  • 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
        }
    }