Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors converting form file to memory stream

I am trying to upload a file and save into Azure Blob storage. The file is injected as a FormFile. The problem is that, there are errors when I convert the FormFile to a memory stream. The stream then uploads to Azure but with no data contained.

 public async Task<IActionResult> Create([Bind("EndorsementId,FileName,ProviderId,Title")] Endorsement endorsement, IFormFile formFile)
    {
        if (ModelState.IsValid)
        {
            ...
            var data = new MemoryStream();

            formFile.CopyTo(data);
            var buf = new byte[data.Length];
            data.Read(buf, 0, buf.Length);

            UploadToAzure(data);

            ...

The errors are on the ReadTimeOut and WriteTimeOut properties of the memory stream. They say 'data.ReadTimeout' threw an exception of type 'System.InvalidOperationException' and 'data.WriteTimeout' threw an exception of type 'System.InvalidOperationException' respectively.

Here is how I injected the FormFile. There seems to be very little information on this. http://www.mikesdotnetting.com/article/288/uploading-files-with-asp-net-core-1-0-mvc

Thanks in advance.

like image 523
Martin Smith Avatar asked Apr 26 '26 09:04

Martin Smith


1 Answers

IFormFile has CopyToAsync method for this purpose. You can just do something like below:

using (var outputStream = await blobReference.OpenWriteAsync())
{
    await formFile.CopyToAsync(outputStream, cancellationToken);
}
like image 200
Kiran Avatar answered Apr 29 '26 00:04

Kiran