Angular 6:从后端服务器获取文件对象后下载文件
Angular 6: Download file after getting File object from backend server
我有一个 File 对象类型的结构 {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`);
});
我有一个 File 对象类型的结构 {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`);
});