gpt4 book ai didi

c# - Angular - 如何在 subscribe() 上从 Web API 下载文件

转载 作者:行者123 更新时间:2023-12-05 03:59:18 26 4
gpt4 key购买 nike

In Angular I'm trying to download an excel file from my Web API Server

如果我从 <a> 调用我的 API组件就像这样:

<a href="http://localhost:55820/api/download">Download</a>

文件下载正常,无需处理响应,我得到了所需的行为:

Success download

如何从我的 Angular DownloadService 发出请求并在 .subscribe() 上处理结果得到相同的结果?

this.downloadService.download()
.subscribe(file => {/*What to put here for file downloading as above*/});

请注意,服务器会像这样创建响应:

byte[] b = File.ReadAllBytes(HttpRuntime.AppDomainAppPath + "/files/" + "file.xlsx");
var dataStream = new MemoryStream(b);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(dataStream);
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "File";
response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping("file.xlsx"));
return response;

提前致谢! :)

最佳答案

试试这个解决办法:

.subscribe(file => 
{
const a = document.createElement('a');
a.setAttribute('type', 'hidden');
a.href = URL.createObjectURL(file.data);
a.download = fileName + '.xlsx';
a.click();
a.remove();
});

关于c# - Angular - 如何在 subscribe() 上从 Web API 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57326028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com