如何从静态后端路径显示 Angular 中的图像?

How to display an image in Angular from a static backend path?

我在后端有一条路径可以保存我的图像。 我可以从 mongo 获取路径并在 angular 中重现它,但是,当我将标签与 src 绑定一起使用时,它不显示图像和任何错误:

组件内部路径:

this.profileService.getImg().subscribe(res => this.imagePath = res['img']);

控制台日志的return:

console.log(this.imagePath);

http://localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg

html标签:

<img [src]="imagePath">

我已经尝试了在其他帖子中找到的几种方法,但无法实现。 知道发生了什么吗?我该如何解决?

更新和更多详细信息

在服务器端,我 return 通过这种方式从 mongo 获取路径:

router.get('/:id', (req, res, next) => {
    Avatar.getAvatarById(req.params.id, (err, avatar) => {
        if(err) throw err;
        if(!avatar){
            return res.json({success: false, msg: 'No avatars found'});
        }
        res.json({
            success: true,
            avatar: avatar
        });
    });
});

其中Avatar.getAvatarById是:

module.exports.getAvatarById = function(id, callback){
    const query = { avatar: {$regex: ".*"+id+".*" }}
    Avatar.findOne(query, callback);
}

我这样公开头像路径:

app.use('/avatars', express.static('avatars'));

当我尝试通过在浏览器中点击 http://localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg 来访问路径时,它 return 是 json 而不是渲染图像。

{
 "success":true,
 "avatar": {
     "_id":"5dc17fc9f383424158c59754", 
     "avatar":"http://localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg","__v":0
 }
}

还尝试通过使用 bypassSecurityTrustResourceUrl 来克服安全问题,并在出现 url 时使用 *ngIf 进行显示。

this.photoUrl = this.sanitizer.bypassSecurityTrustUrl(res['avatar']['avatar']);

<img *ngIf="photoUrl" [src]="photoUrl">

它没有 return 任何错误并且仍然不显示图像。

如果我尝试通过点击 bypassSecurityTrustUrl 函数内的路径进行测试,并删除 *ngIf,它 returns:

null:1 GET http://localhost:4200/null 404 (Not Found)

使用 属性 绑定 应该有效:

 <img [src]="imagePath">

但您也可以尝试 字符串插值:

 <img src="{{imagePath}}">

你尝试了吗

<img [attr.src]="imagePath">

或者万一变更检测是这里的一个问题:

this.imagePath$ = this.profileService.getImg().pipe(
  map(res => res['img']),
);

<img [src]="imagePath$ | async">

您需要将文件从您的 node.js 服务器公开到您的前端。现在,听起来您只是将路径字符串而不是文件本身公开给您的客户端。

您可以通过定义路径来定义 static folder on your server to hold all your static files or by exposing specific files using the res.sendFile 并转到您想要检索该文件的任何文件夹。

使用静态文件夹:

// connect the avatars folder as the `/avatars` server sub path
app.use('/avatars', express.static('avatars'));

使用特定的 res.sendFile:

app.get('/avatars/:name', function (req, res, next) {
  const fileName = req.params.name;
  res.sendFile(fileName, options, function (err) { /* ... */ });
});

取决于您的所有文件是否都位于一个地方,或者用户是否将照片上传到私人位置,您需要使用其中一种方法将文件发送到浏览器,以便浏览器可以访问它.

在我的系统中,我们使用 servlet URL 作为图像 src 标签,来自图像的 servlet returns base64 字符串可以正常工作。

您可以从 Angular 项目中的资产文件夹静态加载图像。您也可以从后端点静态检索图像。您可以通过使用 bypassSecurityTrustResourceUrl

克服 Angular 的安全措施

environment.ts

export const environment = {
  production: false,
  apiURL: 'http://localhost:8080/your-api/v1',
  imageUrl: '/assets/images/yourImage',
};

component.html

<img [src]="imageUrl">

component.ts

photoUrl: SafeResourceUrl;
  ngOnInit() {
    this.urlService.siteProfile.subscribe(s => {
      this.siteProfile = s;
      if(s != null) {
        this.photoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(`${this.apiUrl}/image-directory/your-pic?id`);
      }
    });

在你的帮助下我可以解决这个问题。 但问题不在前端,而实际上在后端。 但是,您的贡献对改进我的代码有很大帮助,所以我会把功劳归功于我可以实施或在我的最终解决方案中遵循建议的每个人。

即使是那些我没有引用的人,我也非常感谢您花时间帮助我!

第一。归功于 @HenryDev

Have you tried putting the image type in the URL? and check if you are able to see the image? just put this in the URl localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg and tell us what you see

试过后我开始认为是我的后端出了问题,因为这次尝试的return是json而不是图像渲染。

第二。归功于 @Thatkookooguy

Using specific res.sendFile:

app.get('/avatars/:name', function (req,
res, next) {   const fileName = req.params.name;  
res.sendFile(fileName, options, function (err) { /* ... */ }); });

在后端,我使用路由查找保存在数据库中具有相同路径的头像'/avatars/:id'。所以每次我尝试访问它时,优先级是路由。

因此,当我尝试通过在浏览器上点击路径访问图像时,它会重新调整 json 文件而不是显示图像。

解决方案

所以,解决方案是替换调用函数获取图像列表的路由!

但是,正如我告诉过你的,我在这里得到了很多提示,这让我有机会改进我的代码:

第三。归功于 @Ian Halfpenny

You can overcome security in place by Angular by using bypassSecurityTrustResourceUrl

所以我使用 bypassSecurityTrustResourceUrl 替换了我的代码。

第四。归功于 @dota2pro

Use *ngIf to display the image after the link was loaded. (It was edited and removed. So, I'm sorry for not showing your original contribution) Now I'm displaying in my html by testing before with *ngIf="avatar"