Parse Image from Microsoft Graph API

旧城冷巷雨未停 提交于 2019-12-11 18:10:58

问题


After i looked up the www, stackoverflow and youtube, i couldn't find an concrete answer about, how to fetch an image correctly from:

https://graph.microsoft.com/beta/me/photo/$value

in TypeScript/JavaScript. The solution is really easier as i thought. You just need this an additional information in your GET Request:

responseType: ResponseContentType.ArrayBuffer

回答1:


The complete solution looks like this:

import { DomSanitizer } from "@angular/platform-browser";
import { Http, Headers, ResponseContentType } from "@angular/http";
import "rxjs/add/operator/map";
import { AlertController } from "ionic-angular";

export class GraphService {
constructor(
   private http: Http,
   private alertCtrl: AlertController,
   private sanitizer: DomSanitizer
) {}

transform(html) {
   return this.sanitizer.bypassSecurityTrustUrl(html);
}

getProfileImage(accessToken: string) {
    // fetch User Profile Image
    let headers: Headers = new Headers();
    headers.append("Authorization", "Bearer " + accessToken);
    this.http
      .get("https://graph.microsoft.com/beta/me/photo/$value", {
        responseType: ResponseContentType.ArrayBuffer,
        headers: headers
      })
      .map(res => res)
      .subscribe(
        (data: any) => {
          let blob = new Blob([data.arrayBuffer()], {
            type: data.headers.get("content-type")
          });
          let imageUrl = window.URL.createObjectURL(blob);

          return this.transform(imageUrl));
        },
        error => {
          let alert = this.alertCtrl.create({
            title: "GraphProvider",
            subTitle: "Can't fetch profile image!",
            buttons: ["OK"]
          });
          alert.present();
        }
      );
}
}

The most important part is: don't append the responseType: ResponseContentType.ArrayBuffer in your header! You have to provide it beside the header! And don't forget to import it from @angular/http!

I hope I could help all the lost souls out there :D

PS: Thanks to Micheal Mainer for the Graph Explorer Repo: https://github.com/microsoftgraph/microsoft-graph-explorer/tree/e2a376615d14c5eabd51e972478b18827800d323

here's my fetched Image from Microsoft Graph API:



来源:https://stackoverflow.com/questions/49181438/parse-image-from-microsoft-graph-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!