Angular 6:从后端服务器获取 File 对象后下载文件 [英] Angular 6: Download file after getting File object from backend server

查看:30
本文介绍了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?

我从这个函数得到我的回应:

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 的格式为 {type: "Buffer", data: Array(702549)}

marketingProposal.materials[0].file is in the format {type: "Buffer", data: Array(702549)}

推荐答案

您可以使用 file-saver 来做到这一点: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆