繁体   English   中英

将图像从 Nodejs 发送到 Angular

[英]Sending image from Nodejs to Angular

我正在尝试将图像从服务器发送到客户端。 经过一番谷歌搜索后,最好的解决方案似乎是将数据作为 ArrayBuffer 发送,然后在 FE 上将其转换为 Blob。 但是,我无法在 FE 上显示图像。 我是否做了一些可能导致问题的转换错误?

对于服务器代码:

exports.getImage = async (req, res) => {

try {
    const file = fs.readFileSync(`${__dirname}/images/image.png`);
    let ab = file.buffer.slice(file.byteOffset, file.byteOffset + file.byteLength);
    return res.status(200).send(ab);
} catch (err) {
    console.log(err);
    return res.status(400).send({
        code: err.errCode,
        description: 'General error'
    });
}

}

在 angular 的接收端:

服务.ts

getCustomMap(groupId: string, mapId: string): Observable<ArrayBuffer> {
        return this._http
            .get(`${this._URL}/${groupId}/customMap/${mapId}`, {
                responseType: 'arraybuffer'
            });
    }

图像组件:

getCustomMap() {
  this._groupManagerService.getCustomMap()
    .subscribe((imgFile: ArrayBuffer) => {
      map.file = new Blob([imgFile], { type: 'image/png' });
      map.url = this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(map.file));
    });
  }

谢谢

只需按照以下步骤操作:

1.服务器/Node.js:

app.get('/', (req, res) => {
    const imageName = "image.png"
    const imagePath = path.join(__dirname, "images", imageName);

    fs.exists(imagePath, exists => {
        if (exists) {
            const { size } = fs.statSync(imagePath);

            res.writeHead(200, {
                'Content-Type': 'image/png',
                'Content-Length': size,
                'Content-Disposition': `attachment; filename='${imageName}`
            });

            fs.createReadStream(imagePath).pipe(res);

        }
        else res.status(400).send('Error: Image does not exists');
    });
})

可选:使用sendFile如下:

app.get('/', (req, res) => {
    const imageName = "image.jpg"
    const imagePath = path.join(__dirname, "images", imageName);

    fs.exists(imagePath, exists => {
        if (exists) res.sendFile(imagePath);
        else res.status(400).send('Error: Image does not exists');
    });
});

2. 客户端 / Angular - 组件:

 public url: SafeResourceUrl;

 constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
   this.getImage('URL').subscribe(x => this.url = x)
 }

 public getImage(url: string): Observable<SafeResourceUrl> {
   return this.http
     .get(url, { responseType: 'blob' })
     .pipe(
       map(x => {
         const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
         return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
       }),
     );
 }

3. 客户 / Angular - 模板:

<img [src]="url">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM