我正在使用express api从服务器下载图像,图像数据以特殊字符形式在前端接收,但图像不下载。我想下载图片。
前端代码:
var array = [10,20,30];
for(var item in array){
console.log(array[item]);
}
创建http get请求的Observable:
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)
});
}
Express js api:
downloadData(id) {
let apiUrl = 'http://localhost:3000/api/download-data/';
return this.http.get(`${apiUrl}${id}`)
.catch((error: Response) => Observable.throw(error.json()));
}
请帮助,如何以特殊字符表示法下载现在接收的图像。我从服务器得到这个响应,我认为图像是以base64格式接收的。
答案 0 :(得分:4)
你只需要告诉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);
}
希望它会有所帮助