How To Use Azure Blobs

  • Uploading a file on the server to a blob.
  • Download a file from a blob to the server.
//src - https://tutorials.visualstudio.com/azure-storage/basic-operations

[Route("api/blobs/upload")]
public async Task UploadFile(string path)
{
    var filePathOnServer = Path.Combine(HostingEnvironment.MapPath(UPLOAD_PATH), path);

    using (var fileStream = File.OpenRead(filePathOnServer))
    {
        var filename = Path.GetFileName(path); // Trim fully pathed filename to just the filename
        var blockBlob = _container.GetBlockBlobReference(filename);

        await blockBlob.UploadFromStreamAsync(fileStream);
    }
}

[HttpGet]
[Route("api/blobs/download")]
public async Task DownloadFile(string blobName)
{
    var blockBlob = _container.GetBlockBlobReference(blobName);

    var downloadsPathOnServer = Path.Combine(HostingEnvironment.MapPath(DOWNLOAD_PATH), blockBlob.Name);

    using (var fileStream = File.OpenWrite(downloadsPathOnServer))
    {
        await blockBlob.DownloadToStreamAsync(fileStream);
    }
}

By: |02/03/2019|categories: /