node.js - 将图像从 Nodejs 发送到 Angular

标签 node.js angular file-transfer

我正在尝试将图像从服务器发送到客户端。经过一番谷歌搜索后,最好的解决方案似乎是将数据作为 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">

关于node.js - 将图像从 Nodejs 发送到 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63700804/

相关文章:

http - request.close 事件不会在 node.js 服务器中触发

node.js - NodeJS 不会提供静态文件,即使使用 express.static

Angular - APP_INITIALIZER - Promise 与 Observable

angular - 如何将注入(inject)服务从父类(super class)继承到 Angular 2 中的子类组件

java - 是否有任何 Java API 可以将文件从一台服务器传输到另一台服务器?

node.js - 如何在服务器上托管React应用程序和 Node API

javascript - 如何在 Visual Studio 2017 中使用 Web 应用程序发布独立的 Angular 组件 (njsproj)

ftp - 什么会超越 FTP,为什么我们还不使用它?

java - 文件发送卡在中间[Socket编程]

Javascript es2015导入语法