Downloading a file from Azure Storage to client using Angular2 with .NET Web Api 2

醉酒当歌 提交于 2019-12-11 13:27:02

问题


I am trying to download a 1GB file from blob storage into the client. I used before Memory Stream and I get OutOfMemory exception.

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.

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?

Thank you!


回答1:


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;



回答2:


I had the same problem.

The Solution I sorted out was -

First thing, the expected behaviour can occur only when client tries to download the file from blob and usually I prefer downloading the file from the client itself.

As in your case, try to get file blob uri and do some operations as below to open file in browser using Angular Router or simply window.location.href.

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

This worked for me.



来源:https://stackoverflow.com/questions/47227123/downloading-a-file-from-azure-storage-to-client-using-angular2-with-net-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!