3

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

6 Comments

Getting syntax error after adding { responseType: "arraybuffer" }, error message says: Argument of type '{ responseType: "arraybuffer"; }' is not assignable to parameter of type 'RequestOptionsArgs'.
Image is still not showing in new window. and not downloading
Can you paste screenshot of response of browser. Do you got buffered response from server?
I have edited the question and provided the screen shot of data coming from server.
Your response is looking fine. Server is sending base64 encoded image. Can you replace your code. I updated my answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.