gpt4 book ai didi

Angular 6 : Download file after getting File object from backend server

转载 作者:行者123 更新时间:2023-12-02 17:23:58 29 4
gpt4 key购买 nike

我有一个结构为 {type: "Buffer", data: Array(702549)} 的文件对象类型,我需要在 Angular 6 中做什么才能在浏览器中下载此文件?

我从这个函数中得到了响应:

  getMarketingProposalById(id: string): Observable<MarketingProposal> {
return this.httpClient.get<MarketingProposal>(this.apiUrl + id , this.httpOptions).pipe(map(marketingProposal => {
if (marketingProposal.materials[0] && marketingProposal.materials[0].file) {
const blob = new Blob([marketingProposal.materials[0].file.data], { type: 'image/png' });
console.log(blob);
// saveAs(blob, 'hello.png');
}
const marketingProposalObject = this.assignMarketingProposalObject(marketingProposal);
this.mapStringToDate(marketingProposalObject);
return marketingProposalObject;
}));
}

marketingProposal.materials[0].file 的格式为 {type: "Buffer", data: Array(702549)}

最佳答案

您可以使用文件保护程序来执行此操作:https://www.npmjs.com/package/file-saver

文件下载代码:

import { saveAs } from 'file-saver';

loadFile(fileId: number) {
try {
let isFileSaverSupported = !!new Blob;
} catch (e) {
console.log(e);
return;
}

this.repository.loadFile(fileId).subscribe(response => {
let blob = new Blob([response.data], { type: 'application/pdf' });
saveAs(blob, `file${fileId}.pdf`);
});
}

更新:我根据负载条件创建了一个测试项目:

http.get('http://localhost:4200/assets/image.png', {responseType: 'blob'}).subscribe(response => {
try {
let isFileSaverSupported = !!new Blob;
} catch (e) {
console.log(e);
return;
}
let blob = new Blob([response], { type: 'image/png' });
saveAs(blob, `file.png`);
});

关于 Angular 6 : Download file after getting File object from backend server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52278535/

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