P. Vitvera
P. Vitvera

Reputation: 95

Sending image from Nodejs to Angular

I'm trying to send an image from the server to the client. After some googling, the best solution seems to send the data as ArrayBuffer and then convert it to Blob on FE. However, I'm not able to get the image to display on FE. Am I doing some conversions wrong that might cause the issue?

For the server code:

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'
    });
}

}

And on the receiving side in angular:

service.ts

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

image component:

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));
    });
  }

Thank you

Upvotes: 2

Views: 2135

Answers (1)

Rafi Henig
Rafi Henig

Reputation: 6414

Simply follow the steps below:

1. Server / 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');
    });
})

Optionally: using sendFile as below:

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. Client / Angular - Component:

 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. Client / Angular - Template:

<img [src]="url">

Upvotes: 2

Related Questions