我希望用户能够从我的网站下载blob.我想要最快/ cheapeast /最好的方式来做到这一点.
这是我想出的:
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();
我现在正在使用内存流,但我猜我应该使用文件流,因为在某些情况下,blob是大的..对吧?
解决方法
恕我直言,最便宜,最快的解决方案是从blob存储直接下载.目前,您的代码首先在您的服务器上下载blob并从那里进行流式传输.您可以做的是创建具有读取权限和Content-Disposition标头集的共享访问签名,并基于该创建blob URL并使用该URL.在这种情况下,blob内容将直接从存储流式传输到客户端浏览器.
例如,看下面的代码:
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); }