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.

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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With