响应包含图像数据,但我无法从响应中提取它。
客户代码 -
download() {
this._http.get('http://localhost:9000/download/' + this._fileid)
.subscribe(
data => {
this.image = data;
},
err => console.log('Error is..:' + err)
);
}
服务器代码 -
app.get('/download/:fileid', function(req, res) {
var id = req.params.fileid;
res.set('Content-Type', 'image/jpeg');
gfs.createReadStream({_id: id}).pipe(res);
});
[编辑] - 我已经调整了我的代码以使用CustomXhr但是我得到一个没有数据的空blob。
CUSTOM XHR CODE -
@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
build(): any {
let xhr = super.build();
xhr.responseType = "blob";
return <any>(xhr);
}
}
BOOTSTRAP代码 -
export function main(initialHmrState?: any): Promise<any> {
return bootstrap(App, [
...ENV_PROVIDERS,
...PROVIDERS,
...DIRECTIVES,
...PIPES,
...APP_PROVIDERS,
provide(BrowserXhr, { useClass: CustomBrowserXhr })
])
.catch(err => console.error(err));
}
HTTP请求 -
download() {
this._http.get('http://localhost:9000/download/' + this._fileid)
.toPromise()
.then(res => {
if (res.headers.get("Content-Type").startsWith("image/")) {
var blob = new Blob([new Uint8Array(res._body)], {
type: res.headers.get("Content-Type")
});
var urlCreator = window.URL;
var url = urlCreator.createObjectURL(blob);
console.log(url);
this.image = url;
}
})
}
答案 0 :(得分:12)
您要找的是arrayBuffer()
。您的代码将是:
download() {
this._http.get('http://localhost:9000/download/' + this._fileid)
.subscribe(
data => {
this.image = data.arrayBuffer();
},
err => console.log('Error is..:' + err)
);
}
但是,不幸的是,arrayBuffer()
尚未实施。{。}。
您可以使用XMLHttpRequest
,Here is a plunker
getImage(url:string){
return Observable.create(observer=>{
let req = new XMLHttpRequest();
req.open('get',url);
req.responseType = "arraybuffer";
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
observer.next(req.response);
observer.complete();
}
};
req.send();
});
}
答案 1 :(得分:0)
事实上,目前并不是那么简单,因为您无法使用Angular2在请求上设置responseType
属性(此时有一个待处理的PR)。
作为一种变通方法,您需要扩展Angular2的BrowserXhr
类,如下所述,在基础xhr对象上设置responseType
到blob
:
import {Injectable} from 'angular2/core';
import {BrowserXhr} from 'angular2/http';
@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
constructor() {}
build(): any {
let xhr = super.build();
xhr.responseType = "blob";
return <any>(xhr);
}
}
然后,您需要将响应有效负载包装到Blog
对象中:
downloadFile() {
this.http.get(
this.http.get(
'https://mapapi.apispark.net/v1/images/sparky_right.png')
.subscribe(
(response) => {
var mediaType = 'image/png';
var blob = new Blob([response._body], {type: mediaType});
(...)
});
}
请参阅此plunkr:请参阅此plunkr:http://plnkr.co/edit/2ZodNBmv8OVj3LZSrozG?p=preview。
有关详细信息,请参阅这些问题: