我正在使用 express api 从服务器下载图像,图像数据以特殊字符形式在前端接收,但图像未下载。我要下载图片。
前端代码:
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)
});
}
创建 http get 请求的 Observable:
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 接口(interface):
router.get('/download-data/:id', function (req, res, next) {
Workshop.findById(req.params.id).then((task) => {
res.download(task.workshopData,'me.jpg')
}).catch(next);
});
请帮忙,如何以特殊字符表示法下载正在接收的图像。我从服务器收到此响应,我认为图像是以 base64 格式接收的。
最佳答案
你只需要告诉 Angular 你想要以流而不是 json 的形式响应。使用以下代码:
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()));
}
用以下内容替换服务:
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);
}
希望对你有帮助
关于Angular 2+从服务器下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48184922/