Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Image Data from response: Angular 2

Tags:

angular

The response has the image data but I am unable to extract it from the response.

CLIENT CODE-

download() {
    this._http.get('http://localhost:9000/download/' + this._fileid)
    .subscribe(
    data => {
        this.image = data;
    },
    err => console.log('Error is..:' + err)
    );
}

SERVER CODE-

app.get('/download/:fileid', function(req, res) {
    var id = req.params.fileid;
    res.set('Content-Type', 'image/jpeg');
    gfs.createReadStream({_id: id}).pipe(res);
});

[EDIT]- I have adapted my code to use CustomXhr but however I get an empty blob with no data.

CUSTOM XHR CODE-

@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
  build(): any {
    let xhr = super.build();
    xhr.responseType = "blob";
    return <any>(xhr);
  }
}

BOOTSTRAP CODE-

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 REQUEST-

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;
      }
    })
}
like image 490
shiv Avatar asked Apr 06 '16 06:04

shiv


1 Answers

What you are looking for is arrayBuffer(). Your code will be:

download() {
    this._http.get('http://localhost:9000/download/' + this._fileid)
    .subscribe(
    data => {
        this.image = data.arrayBuffer();
    },
    err => console.log('Error is..:' + err)
    );
}

But, unfortunately, arrayBuffer() is not yet implemented as of beta.13.

You could instead use 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();
 });
}
like image 130
Abdulrahman Alsoghayer Avatar answered Nov 13 '22 06:11

Abdulrahman Alsoghayer