首页 > 解决方案 > 如何从 MEAN 堆栈应用程序的组件 Ts 中的后端获取图像

问题描述

我需要从 backend/images 文件夹中获取图像作为 component.ts 文件中的 Image 对象。我可以从数据库中获取图像的路径。

this.productsService.getProduct(this.editId).subscribe(productData => {
    this.name = productData.name;
    this.code = productData.code;
    this.category = productData.category;
    this.description = productData.description;
    this.details = productData.details;
    this.editImagePaths = productData.imagePaths;
  });

我尝试通过 http 请求获取图像。

for (let i = 0; i < this.editImagePaths.length; i++) {


      this.http.get<File>(this.editImagePaths[i]).subscribe(value => {

        this.images.push(value);
      });
    }

images 是一个文件类型的数组。问题是 http.get 返回 blob 字符串,而 core.js 给出以下错误;

core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: " http://localhost:3000/images/asd0-1575503057766.png ", ok: false, ...} 错误: {error: SyntaxError: Unexpected token � in JSON at position 0 at JSON.parse () at XMLHtt…, text: "�PNG ↵↵ IHDRI������PLTE�F���+*)...�LЙ� 3 @����������y�(pIEND�B`�"} 标头:HttpHeaders {normalizedNames:Map(0),lazyUpdate:null,lazyInit:ƒ} 消息:“解析http:/期间的 Http 失败/localhost:3000/images/asd0-1575503057766.png “名称:“HttpErrorResponse” ok:false 状态:200 statusText:“OK” url:“ http://localhost:3000/images/asd0-1575503057766.png原型: HttpResponseBase

标签: node.jsangulartypescriptexpress

解决方案


您需要将响应解析为 ablob而不是 ajson

this.http.get<File>(this.editImagePaths[i], {responseType: 'blob'})
    .subscribe(value => this.images.push(value));

推荐阅读