将图像从 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 中的接收端:

service.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">