Angular 6:从后端服务器获取File对象后下载文件 [英] Angular 6: Download file after getting File object from backend server
本文介绍了Angular 6:从后端服务器获取File对象后下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个结构为{type:"Buffer",data:Array(702549)}的File对象类型,我需要在angular 6中做什么才能在浏览器中下载该文件?
I have a File object type of structure {type: "Buffer", data: Array(702549)}, what do I need to do in angular 6 in order to download this file in browser?
我从此函数得到响应:
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)}
marketingProposal.materials[0].file is in the format {type: "Buffer", data: Array(702549)}
推荐答案
您可以使用文件保护程序来执行此操作: https://www.npmjs.com/package/file-saver
You can use file-saver to do this: 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: I'v created a test project according to load conditions:
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:从后端服务器获取File对象后下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文