Azure download blob filestream/memorystream

后端 未结 2 1523
我寻月下人不归
我寻月下人不归 2020-12-18 01:43

I want users to be able to download blobs from my website. I want the fastest/cheapeast/best way to do this.

Heres what i came up with:

        Cloud         


        
相关标签:
2条回答
  • 2020-12-18 01:56

    Your code is almost right. Try this:

        public virtual ActionResult DownloadFile(string name)
        {
            Response.AddHeader("Content-Disposition", "attachment; filename=" + name); // force download
            CloudBlobContainer blobContainer = CloudStorageServices.GetCloudBlobsContainer();
        CloudBlockBlob blob = blobContainer.GetBlockBlobReference(blobName);
            blob.DownloadToStream(Response.OutputStream);
            return new EmptyResult();
        }
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-18 02:08

    IMHO, the cheapest and fastest solution would be directly downloading from blob storage. Currently your code is first downloading the blob on your server and streaming from there. What you could do instead is create a Shared Access Signature with Read permission and Content-Disposition header set and create blob URL based on that and use that URL. In this case, the blob contents will be directly streamed from storage to the client browser.

    For example look at the code below:

        public ActionResult Download()
        {
            CloudStorageAccount account = new CloudStorageAccount(new StorageCredentials("accountname", "accountkey"), true);
            var blobClient = account.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference("container-name");
            var blob = container.GetBlockBlobReference("file-name");
            var sasToken = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
                {
                    Permissions = SharedAccessBlobPermissions.Read,
                    SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(10),//assuming the blob can be downloaded in 10 miinutes
                }, new SharedAccessBlobHeaders()
                {
                    ContentDisposition = "attachment; filename=file-name"
                });
            var blobUrl = string.Format("{0}{1}", blob.Uri, sasToken);
            return Redirect(blobUrl);
        }
    
    0 讨论(0)
提交回复
热议问题