我有一个结构为 {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 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`);
});
}
UPDATE:我根据负载条件创建了一个测试项目:
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`);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)