Azure下载blob文件流/ memorystream

时间:2014-05-22 12:58:55

标签: asp.net-mvc azure

我希望用户能够从我的网站下载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是大的..对吧?

我尝试使用文件流,但我失败了。想想你能给我一些文件流代码吗?

2 个答案:

答案 0 :(得分:16)

恕我直言,最便宜,最快的解决方案是直接从blob存储下载。目前,您的代码首先在您的服务器上下载blob并从那里进行流式传输。您可以做的是创建Shared Access Signature Read权限和Content-Disposition标头集,并根据该URL创建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);
    }

答案 1 :(得分:1)

您的代码几乎是正确的。试试这个:

    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();
    }

希望这会有所帮助。