Azure download blob filestream / memorystream

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

Here is what I came up with:

CloudBlobContainer blobContainer = CloudStorageServices.GetCloudBlobsContainer(); CloudBlockBlob blob = blobContainer.GetBlockBlobReference(blobName); MemoryStream memStream = new MemoryStream(); blob.DownloadToStream(memStream); Response.ContentType = blob.Properties.ContentType; Response.AddHeader("Content-Disposition", "Attachment; filename=" + fileName + fileExtension); Response.AddHeader("Content-Length", (blob.Properties.Length).ToString()); Response.BinaryWrite(memStream.ToArray()); Response.End(); 

Now I use memystream, but I guess I have to go with filestream, because of the blobs, in some cases, big .. Is that right?

I tried this with filestream, but I failed. I think you could give me a pass code?

+7
asp.net-mvc azure
source share
2 answers

IMHO, the cheapest and fastest solution will be directly downloaded from the blob repository. At the moment, your code first downloads blob to your server and passes from there. Instead, you can create a Shared Access Signature permission with Read and Content-Disposition permission and create a blob URL on it and use that URL. In this case, the blob content will be directly transferred from the repository 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); } 
+12
source share

Your code is almost right. Try the following:

  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.

+1
source share

All Articles