0

I have an Azure application built with ASP.NET Core using the MVC pattern. Document uploads are stored in Azure Blob Containers and the C# upload code I wrote is working great. I am using Azure.Storage.Blobs version 12.14.1

Here is my download blob code:

//get document metadata stored in sql table, id comes from a method param
var document = _unitOfWork.Documents.GetById(id);
if (document == null)
{
   throw new FileNotFoundException();
}
                
//get connection and container from appsettings.json
string connection = _appConfig.AzureStorageConnection;
string containerName = _appConfig.AzureStorageContainer;

//work with blob client
var serviceClient = new BlobServiceClient(connection);
var container = serviceClient.GetBlobContainerClient(containerName);
var fileName = document.UniqueDocumentName;
var blobClient = container.GetBlobClient(document.UniqueDocumentName);

using (FileStream fileStream = System.IO.File.OpenWrite("<path>"))
{
   blobClient.DownloadTo(fileStream);
}

After I get to using code to set up the file stream, I don't understand what to pass into the OpenWrite method as a path. This application is a B2C app and so how do I just prompt a user to download the file?

I do get a file download with the above code but the file is called download.xml. That is not the file that should be downloaded. I expected the download file to be an .odt file.

Documentation seems to be very sparse on downloading from Azure Blob Storage

EDIT 1. I got rid of the FileStream and did this instead:

MemoryStream ms = new MemoryStream();
ms.Position = 0;
blobClient.DownloadTo(ms);
return new FileStreamResult(ms, document.FileType);
Ryan
  • 650
  • 3
  • 15
  • 49
  • I’m assuming that the code to download the blob is running server side and you want the file to be saved on client side (browser prompting the user to save the file locally). Am I correct? – Gaurav Mantri Jan 21 '23 at 17:47
  • That is correct. – Ryan Jan 21 '23 at 17:50
  • You don't need to use FileStream. Just download the blob content in memory stream and send it back to the client as `FileResult`. Please see this for example: https://stackoverflow.com/a/34498356/188096. – Gaurav Mantri Jan 21 '23 at 17:53
  • Thanks. Got it working. Commented in my original post. Form up and answer and I will make it as such. – Ryan Jan 21 '23 at 19:09
  • Please post your edit as an answer. – Gaurav Mantri Jan 22 '23 at 18:25

1 Answers1

0

I did this instead of using FileStream and returned FileResult instead:

MemoryStream ms = new MemoryStream();
ms.Position = 0;
blobClient.DownloadTo(ms);
return new FileStreamResult(ms, document.FileType);
Ryan
  • 650
  • 3
  • 15
  • 49