【问题标题】:How to get image from node-express and view the image in Angular 8如何从 node-express 获取图像并在 Angular 8 中查看图像
【发布时间】:2019-11-27 18:29:35
【问题描述】:

我尝试从后端获取图像并在我的 Angular 应用程序中查看并失败。

我的服务器路由:

app.get("/signature/:id", (req,res) => {
  res.send("./dest/signature.png");
})

客户服务:

  image() {
    return this.http.request('GET', this.baseUrl + '/signature/' + '1', {responseType: 'blob'}).toPromise();
  }

组件

 ngOnInit(){
 this.service.image().then((image) => {
      const imageURL = URL.createObjectURL(image);
      this.image = imageURL;
    });
}

我在浏览器上的错误:

core.js:6629 WARNING: sanitizing unsafe URL value blob:http://localhost:4200/406c69e3-93b6-4c00-8ec8-b43c7f266737 (see http://g.co/ng/security#xss)

unsafe:blob:http://localhost:4200/406c69e3-93b6-4c00-8ec8-b43c7f266737:1 GET unsafe:blob:http://localhost:4200/406c69e3-93b6-4c00-8ec8-b43c7f266737 net::ERR_UNKNOWN_URL_SCHEME

【问题讨论】:

    标签: node.js angular express


    【解决方案1】:

    您可以创建一个管道来绕过这个问题。

    ng g pipe safeHtml
    

    管道.ts:

    @Pipe({
      name: 'safeHtml'
    })
    export class SafeHtmlPipe implements PipeTransform {
    
      constructor(private sanitizer: DomSanitizer) {
      }
    
      transform(value: any, args?: any): any {
        return this.sanitizer.bypassSecurityTrustHtml(value);
      }
    
    }
    

    在您的模板中,只需编写

    <img [src]="image | safeHtml"></div>
    

    【讨论】:

    • 出色的工作,将服务器更改为“sendfile”
    【解决方案2】:

    正确的 API 是:sendFile

    http://expressjs.com/en/api.html
    

    其他方式:

    1. 您可以返回图像流。
    2. 您可以将您的图像放在某个公开的地方。并且可以只返回该图片的 URL。

    【讨论】:

    • 谢谢,我把它改成“sendfile”,它和角度的安全管道一起工作
    【解决方案3】:

    您不需要基于某个 Image 对象创建图像 URL。只需从后端获取图像的完整路径 URL,然后使用 img 标签将其显示在您的 Angular 应用程序中即可。

     <img [src]="{{res.img_url}}" alt="image-txt">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多