在节点服务器上的角度应用程序上显示图像

时间:2018-06-26 15:33:55

标签: node.js angular multer

我有一个运行在localhost:3000上的nodejs应用程序,我使用multer上传了图像,因此它们位于./uploads/文件夹中。 在locahost:4200上运行的Angular应用中,我想检索那些图像。

在我的for循环中:( projectImages是每个Project Object的图像数组)

<div *ngFor="let i of project.projectImages">
   <img [src]=i.path alt="" > 
</div>

问题在于路径显示为:localhost:4200 / uploads / image.png而不是localhost:3000 / uploads / image.png

更新: 通过向组件添加变量来解决该问题,现在我得到了:

WARNING: sanitizing unsafe URL value 

任何帮助将不胜感激!

UPDATE2 : 这是我的组件:

    import { Component, OnInit } from '@angular/core';
import { ProjectService } from '../services/project.service';
import { Router, ActivatedRoute } from '@angular/router';
import {Location} from '@angular/common';
import { DomSanitizer } from '@angular/platform-browser';


@Component({
  selector: 'app-project-details',
  templateUrl: './project-details.component.html',
  styleUrls: ['./project-details.component.css']
})
export class ProjectDetailsComponent implements OnInit {
  project:any;
  apiUrl :string = "localhost:3000";
  project_id:string;

  constructor(
    private router:Router,
    private activatedRoute: ActivatedRoute,
    private projectService:ProjectService,
    private _location: Location,
    private sanitization: DomSanitizer
  ) {
    this.activatedRoute.params
    .subscribe( params => {
      console.log(params.project_id)
      this.project_id = params.project_id;
      this.getProjectByID(params.project_id);
    })
   }

  ngOnInit() {
  }

getProjectByID(project_id:string){
  this.projectService.getProjectById(project_id).subscribe((data:any) => {
    this.project = data.project;
    this.project.projectImages.map(image => {
      image.path = this.sanitization.bypassSecurityTrustUrl(`${this.apiUrl}/${image.path}`.replace(/\\/g,"/"));
      console.log(image);
      return image;
});
    console.log(this.project.projectImages); 
  } , err => {
    console.log(err);
  });
}
}

注意:project.projectImages是一个包含图像的数组,看起来是这样的:https://ibb.co/jEgszo

2 个答案:

答案 0 :(得分:0)

使用完整路径并在使用前清理URL

std::reverse_iterator

然后在您的HTML中可以执行此操作

import { DomSanitizer } from '@angular/platform-browser';
import { environment } from '../../../../environments/environment';

export class YourClass{
  project;
  apiUrl;

  constructor(private sanitization: DomSanitizer) {
      this.apiUrl = environment.apiUrl;
      project.projectImages.map(image => {
        image.path = this.sanitization.bypassSecurityTrustUrl(`${this.apiUrl}/${image.path}`);
        return image;
  });
  }
}

您的完整代码将如下所示

<div *ngFor="let i of project.projectImages">
   <img [src]=i.path alt="" > 
</div>

}

签出文档here

答案 1 :(得分:0)

我猜您在节点应用程序中使用了express,您需要包括一条指向resources / uploads目录的静态路由(表达静态路由),如下所示:

app.use(express.static('resources / uploads'))