【问题标题】:Downloading a file from Azure Storage to client using Angular2 with .NET Web Api 2使用 Angular2 和 .NET Web Api 2 将文件从 Azure 存储下载到客户端
【发布时间】:2019-04-09 23:10:02
【问题描述】:

我正在尝试从 blob 存储下载一个 1GB 的文件到客户端。我在 Memory Stream 之前使用过,我得到 OutOfMemory 异常。

现在我正在尝试从 blob 打开读取流并将其直接发送到客户端。

 [HttpGet]
 [ResponseType(typeof(HttpResponseMessage))]
 public async Task<HttpResponseMessage> DownloadAsync(string file)
 {
     HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
     var stream = await blob.OpenReadAsync("container", file);
     result.Content = new StreamContent(stream);
     return result;
 }

文件下载正确,但问题是:代码在客户端下载完整的流,然后客户端看到下载的文件。 我希望客户端看到文件正在下载,所以用户知道他正在下载一些东西。不只是阻止请求并等待它完成。

我在 Angular2 中使用 FileSaver:

this.controller.download('data.zip').subscribe(
      data => {
        FileSaver.saveAs(data, 'data.zip');
      });

有人知道如何解决吗?

谢谢!

【问题讨论】:

  • 您找到解决方案了吗?
  • @Neel 不幸的是,不是!如果您找到了问题的解决方案,请随时将其添加为答案,以便其他开发人员可以从中学习。谢谢!
  • @SamySammour 我也有类似的问题。请问你是怎么解决的?
  • @ark 不,我确实直接从 Blob 存储而不是服务器下载了该项目

标签: download stream azure-blob-storage


【解决方案1】:

要修复它,您需要改用以下 javascript 代码:

var fileUri = "http://localhost:56676/api/blobfile";  //replace with your web api endpoint
var link = document.createElement('a');
document.body.appendChild(link);
link.href = fileUri;
link.click();

然后在你的后端,像这样:

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = await blob.OpenReadAsync("container", file);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "data.zip"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;

【讨论】:

  • 很遗憾,它并没有解决问题。下载仍然没有出现在浏览器下载中。但是当 Google Chrome 中的网络选项卡打开时,它会在请求中运行。
  • 它对我有用。测试的时候清除浏览器缓存了吗?
【解决方案2】:

我遇到了同样的问题。

我整理出来的解决方案是——

首先,只有当客户端尝试从 blob 下载文件时才会发生预期的行为,通常我更喜欢从客户端本身下载文件。

在您的情况下,尝试获取文件 blob uri 并执行以下操作以使用 Angular 路由器或简单的 window.location.href 在浏览器中打开文件。

window.location.href = “https://*/filename.xlsx”

这对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-24
    • 2014-11-22
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多