问题
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?
I get my response from this function:
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 is in the format {type: "Buffer", data: Array(702549)}
回答1:
You can use file-saver to do this: https://www.npmjs.com/package/file-saver
File download code:
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`);
});
来源:https://stackoverflow.com/questions/52278535/angular-6-download-file-after-getting-file-object-from-backend-server