使用Angular2和.NET Web Api 2将文件从Azure存储下载到客户端 [英] Downloading a file from Azure Storage to client using Angular2 with .NET Web Api 2
问题描述
我正在尝试从Blob存储中下载一个1GB的文件到客户端.我在Memory Stream之前使用过,并且得到OutOfMemory异常.
I am trying to download a 1GB file from blob storage into the client. I used before Memory Stream and I get OutOfMemory exception.
现在,我正在尝试从Blob中打开读取流,并将其直接发送到客户端.
now I am trying to open a read stream from the blob and send it directly to the client.
[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;
}
文件已正确下载,但问题是:代码在客户端中下载了完整的流,然后客户端看到了下载的文件. 我希望客户端看到文件正在下载,因此用户知道他正在下载某些内容.不仅阻止请求,然后等到完成.
The file is downloaded correctly, but the problem is: The code download the complete stream in the client, then the client sees the downloaded file. I wanted the client to see the file as being downloaded, so the user knows that he is downloading something. Not just blocking the request and wait till it finished.
我正在Angular2中使用FileSaver:
I am using FileSaver in Angular2:
this.controller.download('data.zip').subscribe(
data => {
FileSaver.saveAs(data, 'data.zip');
});
有人知道如何解决吗?
Has anybody an idea how to fix it?
谢谢!
推荐答案
要解决此问题,您需要使用以下JavaScript代码代替:
To fix it you'd need to use the following javascript code instead:
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();
然后在您的后端中将其设置为这样:
And then in your backend, make it like so:
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;
这篇关于使用Angular2和.NET Web Api 2将文件从Azure存储下载到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!