Azure Blob storage: DownloadToByteArray VS DownloadToStream

后端 未结 3 1317
别跟我提以往
别跟我提以往 2021-01-31 14:42

I have been playing with the Azure Blob Storage service to save/recover files in a context of a web page to be hosted in Azure Web Pages.

During the learning process I h

3条回答
  •  囚心锁ツ
    2021-01-31 15:27

    Instead of streaming the blob through your server, you could download it directly from the blob storage. My answer is built on top of Steve's response here: Downloading Azure Blob files in MVC3. For downloading a blob directly from the storage, you would utilize Shared Access Signature (SAS). Recently Azure Storage has introduced an enhancement, which allows you to specify Content-Disposition header in SAS. See this modified code.

        public static string GetDownloadLink(string fileName)
        {
            CloudBlobContainer container = GetBlobContainer();
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
            //Create an ad-hoc Shared Access Policy with read permissions which will expire in 12 hours
            SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
            {
                Permissions = SharedAccessBlobPermissions.Read,
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(12),
            };
            //Set content-disposition header for force download
            SharedAccessBlobHeaders headers = new SharedAccessBlobHeaders()
            {
                ContentDisposition = string.Format("attachment;filename=\"{0}\"", fileName),
            };
            var sasToken = blockBlob.GetSharedAccessSignature(policy, headers);
            return blockBlob.Uri.AbsoluteUri + sasToken;
        }
    
        public ActionResult Download(string fileName)
        {
            var sasUrl = GetDownloadLink(fileName);
            //Redirect to SAS URL ... file will now be downloaded directly from blob storage.
            Redirect(sasUrl);
        }
    

提交回复
热议问题