微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将图像从Nodejs发送到Angular

如何解决将图像从Nodejs发送到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'
    });
}

}

在接收端成角度:

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('/',res) => {
    const imageName = "image.jpg"
    const imagePath = path.join(__dirname,exists => {
        if (exists) res.sendFile(imagePath);
        else res.status(400).send('Error: Image does not exists');
    });
});

2。客户端/角度-组件:

 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。客户端/角度-模板:

<img [src]="url">

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。