【问题标题】:How to get images from backend in component Ts in MEAN stack app如何从 MEAN 堆栈应用程序的组件 Ts 中的后端获取图像
【发布时间】:2020-03-30 19:25:52
【问题描述】:

我需要从 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 错误 HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:3000/images/asd0-1575503057766.png", ok: false, …} 错误:{error: SyntaxError: Unexpected token � in JSON at JSON.parse () at XMLHtt...,文本:“�PNG ↵↵ IHDRI������PLTE�F���+*)…�LЙ�3 @������������y�(pIEND�B`�"} 标头:HttpHeaders {normalizedNames:Map(0),lazyUpdate:null,lazyInit:ƒ} 消息:“http://localhost:3000/images/asd0-1575503057766.png 解析期间的 Http 失败” 名称:“HttpErrorResponse” 好的:假的 状态:200 状态文本:“确定” 网址:“http://localhost:3000/images/asd0-1575503057766.png原型:HttpResponseBase

【问题讨论】:

  • 您的内容类型可能是application/json,而不是image/png。尝试用邮递员或其他方式来缩小你的问题。 (把 angular/HttpClient 去掉)

标签: node.js angular typescript express


【解决方案1】:

您需要将响应解析为 blob 而不是 json

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

【讨论】:

【解决方案2】:

首先,这取决于您如何将图像存储为 blob 或数据库中的 URL/路径。但是,我建议存储图像的路径,同时将图像上传到服务器上的文件夹。

现在,如果是路径,只需通过普通的 get 请求或 angular 的 post 请求获取服务器上图像的路径。

export class ComponentName{

products: any;

constructor(
 private service: ServiceComponent
){}

this.service.productList(values).subscribe(data => {
  this.product = data;
})

}

另外,如果您注意到我是如何使用一个变量来存储所有数据的;类别、图像和其他。现在,如果我想显示我的图像,我会在我的 component.html 中这样做

<img *ngFor="let images of product.imagePaths" [src]="images">

最后,请检查您存储数据的方式以及发回数据的方式。它很重要。我的模式只存储图像路径,即使在数组中并将图像检索为 json-array .....

【讨论】:

    【解决方案3】:

    尝试将 responseType 更改为 'blob'

    this.httpClient.get(imageList, { responseType: 'blob' }).subscribe(value => {
       this.images.push(value);
    });
    

    【讨论】:

    • 我也试过了。有结果。 imgur.com/a/YnHx4ZN
    • 你使用的是HttpClient还是HttpClientModule?
    • 您是否也尝试过没有像上面示例中那样的类型? this.http.get&lt;File&gt;(... > this.httpClient.get(...
    • @nullptr.t 我正在使用 HttpClient
    猜你喜欢
    • 2020-01-27
    • 2019-07-29
    • 2021-02-25
    • 2019-11-24
    • 2017-03-18
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多