Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2+ downloading image from server

I am working to download image from server using express api, Image data is receiving in front end in special characters form, but image does not download. I want to download the image.

Front end code:

downloadFile(data: Response) {
    var blob = new Blob([data], { type: 'image/jpeg' });
    var url = window.URL.createObjectURL(blob);
    window.open(url);
  }

  downloadData() {        
    this.workshopService.downloadData(this.workshop.id)
      .subscribe((result) => {
        this.downloadFile(result)            
      }, error => {
        console.log(error)           
      });
  }

Observable which creates http get request:

downloadData(id) {
    let apiUrl = 'http://localhost:3000/api/download-data/';            
    return this.http.get(`${apiUrl}${id}`)         
      .catch((error: Response) => Observable.throw(error.json()));
  }  

Express js api:

router.get('/download-data/:id', function (req, res, next) {       
    Workshop.findById(req.params.id).then((task) => {            
        res.download(task.workshopData,'me.jpg')
    }).catch(next);
});

Please help, how to download the image that is receiving now in special characters notation. I am getting this response from server, I think the image is receiving in base64 format.

enter image description here

like image 320
Waleed Shahzaib Avatar asked May 20 '26 10:05

Waleed Shahzaib


1 Answers

You just need to tell angular that you want response as stream rather than json. Use following code:

import { ResponseContentType } from '@angular/http';


downloadData(id) {
    let apiUrl = 'http://localhost:3000/api/download-data/';            
    return this.http.get(`${apiUrl}${id}`, { responseType: ResponseContentType.ArrayBuffer })         
      .catch((error: Response) => Observable.throw(error.json()));
  }  

Replace service with following:

downloadFile(data: Response) {
    console.log(data);
    // may be you need to use data._body to get data of body
    var blob = new Blob([data], { type: 'image/jpeg' });
    var url = window.URL.createObjectURL(blob);
    window.open(url);
  }

Hope it will help

like image 86
Sandip Jaiswal Avatar answered May 23 '26 03:05

Sandip Jaiswal