Load images from Restful Service


#1

I need to load images from Dropbox (RestApi).
For which I have a service to fetch data.
I have tried several ways to load data -

  1. ‘data:image/jpeg;base64,’ + response
  2. Setting into blob but seems somewhere I missing.

Service

getFullImage() {
    let url = "http:mydropboxImageURL";

    let headerArgs  = new Headers();
    headerArgs.append("Content-Type", 'application/jpeg');
    headerArgs.append('Authorization', 'Bearer Access Token');
    console.log("In get request...");

    let options = new RequestOptions({ headers: headerArgs });

    return this._http.get(url,  options) 
      .map((res: Response) => res)
      .subscribe(
        data => {
          if(data.status == 200)
            console.log(data); //Getting proper response. here
            return data;  //Should be Data._body. But getting error.
          },
        err => { console.error('An error occurred', err) }
      );
  }

Component:

this.ImgVar=  this._myService.getFullImage();

Template:

<img id="myImage" src="{{ImgVar}} " border="0" /> //How to render here

#2
class ImageService {
  constructor(private _http: Http, private _sani: DomSanitizer) {}

  getFullImage(): Observable<SafeUrl> {
    ... url and header stuff
    return this._http.get(url, options)
      .map(rsp => this._sani.bypassSecurityTrustUrl(rsp.text()));
  });
}

sanimg: SafeUrl;

constructor(imgs: ImageService) {
  imgs.getFullImage().subscribe(sanimg => this.sanimg = sanimg);
}

<img [src]="sanimg">

#3

Didn’t try .text(). I will try this this.


#4

Make sure you stop doing what you are doing in terms of subscribing within getFullImage().


#5

I am getting Error:

If:  <img id="bigPicture" [src]='sanimg'/>
http://localhost:8100/null 404 (Not Found)

If:   <img id="bigPicture" src='{{sanimg}}'/>
I read somewhere that this bining should not use if variable is non-text

Error is: unsafe:SafeValue must use [property]=binding: blob:http://localhost:8100/8e5c1cc6-d784-4844-b0d3-e9d16732d114 (see http://g.co/ng/security#xss):1 GET unsafe:SafeValue must use [property]=binding: blob:http://localhost:8100/8e5c1cc6-d784-4844-b0d3-e9d16732d114 (see http://g.co/ng/security net::ERR_UNKNOWN_URL_SCHEME

#6

That should be safely ignorable and resolve itself once the http request has come back. If you wish, you can fence the image off with *ngIf or fill sanimg with a safe dummy placeholder URL in an initializer.


#7

I know this problem is not related to ionic but Angular. However I am hoping to get it worked.
I have used the code and I am able to get response and set it into "sanimg"
However, browser not able to render the image.
I am getting like HTML like

<img id="bigPicture" src="����JFIF ..." >

I am using dropbox api and content-type is application/octet-stream .
I tried converting response into blob

.map(res => {
        return new Blob([res['_body']], {
          type: 'application/jpeg'
        });
      })
      .map(blob => {
        var urlCreator = window.URL;
        return  this.sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
      })

In final  html Code: no object preview in generated URL, chrome developer tool -> network tab
<img id="bigPicture" src="blob:http://localhost:8100/fe6bce7b-106f-4b84-8c9f-a7628cdaf3a4">

I am stuck here.


#8

Convert it to a data URI instead of raw binary.


#9

Tried even Data URI. Didn’t worked.
Finally able to worked it out
Here is magic extracted from Dropbox code lookup

let options = new RequestOptions({ headers: headerArgs, responseType: ResponseContentType.ArrayBuffer}); //responseType added here
    return this._http.get(url, options)
      .map(res => {
        return res;
      })
      .map(resp => {
        console.log(resp);
        var urlCreator = window.URL;
        const toDownload: Blob = new Blob([resp.arrayBuffer()], {type: 'application/octet-stream'}); //and this type:
        
        return  this.sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(toDownload));
      })

Thanks a lot bearing with me.
However, I am surprised that Dropbox api sending plain .ts file.
Have a look source of: https://dropbox.github.io/dropbox-api-v2-explorer/#files_get_thumbnail

:slight_smile: