Search code examples
c#asp.net-coregarbage-collectionasp.net-core-webapidispose

Upload large file to API and store it ti blob


I have simple web api controller with action

[HttpPost]
public async Task<IActionResult> Add(IFormFile file)
{
    var firmware = await _firmwareManager.Add(
        new FirmwareAddDto
        {
            Name = file?.FileName,
            Version = version,
            Data = file?.OpenReadStream()
        });

    return StatusCode((int)HttpStatusCode.Created, firmware);
}

then in manager I have this code that store stream to azure blob storage

byte[] data = firmwareAddDto.Data.ToByteArray();
var blob = await _fileStorage.Add("filename", data);

Should I dispose something here? I'm going to upload a large files. Please advice if it will disposing correctly


Solution

  • For large files, I advise you to copy the incoming stream into the outgoing stream, to avoid having to keep all file in memory inside the byte array.

    Assuming that you have a method in the fileStorage that supports streams you can dispose it after you call the Add method. As you can see in the example bellow:

     using(var incomingStream = file.OpenReadStream())
     {
         var firmware = await _firmwareManager.Add(
            new FirmwareAddDto
            {
                Name = file?.FileName,
                Version = version,
                Data = incomingStream 
            });
         (...)
      }
    

    then in the manager, you can call the method with the stream:

    var blob = await _fileStorage.Add("filename", firmwareAddDto.Data);