Angular 2+从服务器下载图像

标签 angular image express download

我正在使用 express api 从服务器下载图像,图像数据以特殊字符形式在前端接收,但图像未下载。我要下载图片。

前端代码:

downloadFile(data: Response) {
    var blob = new Blob([data], { type: 'image/jpeg' });
    var url = window.URL.createObjectURL(blob);
    window.open(url);
  }

  downloadData() {        
    this.workshopService.downloadData(this.workshop.id)
      .subscribe((result) => {
        this.downloadFile(result)            
      }, error => {
        console.log(error)           
      });
  }

创建 http get 请求的 Observable:

downloadData(id) {
    let apiUrl = 'http://localhost:3000/api/download-data/';            
    return this.http.get(`${apiUrl}${id}`)         
      .catch((error: Response) => Observable.throw(error.json()));
  }  

Express js 接口(interface):

router.get('/download-data/:id', function (req, res, next) {       
    Workshop.findById(req.params.id).then((task) => {            
        res.download(task.workshopData,'me.jpg')
    }).catch(next);
});

请帮忙,如何以特殊字符表示法下载正在接收的图像。我从服务器收到此响应,我认为图像是以 base64 格式接收的。

enter image description here

最佳答案

你只需要告诉 Angular 你想要以流而不是 json 的形式响应。使用以下代码:

import { ResponseContentType } from '@angular/http';


downloadData(id) {
    let apiUrl = 'http://localhost:3000/api/download-data/';            
    return this.http.get(`${apiUrl}${id}`, { responseType: ResponseContentType.ArrayBuffer })         
      .catch((error: Response) => Observable.throw(error.json()));
  }  

用以下内容替换服务:

downloadFile(data: Response) {
    console.log(data);
    // may be you need to use data._body to get data of body
    var blob = new Blob([data], { type: 'image/jpeg' });
    var url = window.URL.createObjectURL(blob);
    window.open(url);
  }

希望对你有帮助

关于Angular 2+从服务器下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48184922/

相关文章:

javascript - RxJS combineLatest 与 Angular 中的 startsWith 给出错误

jquery - 为什么网页上没有显示高度和宽度?

image - DXF图像实体组码解释

html - Node.js( express ): How to include correct value for 'src' attribute of an 'img' tag?

typescript - 什么是 Angular 2 中的 `change` 事件

http - 如何使用 angular2 http API 跟踪上传/下载进度

Angular 6 ng-bootstrap 评级不起作用

C# HTML 字符串 -> 获取没有 html 的长度

node.js - 如何包含 'many' 模型中关系的 'one of many' 部分?

javascript - 表达 Mongoose 在找到后在 View 上显示数据