有没有一种简单的方法可以在 React 应用程序中显示图形 api 中的个人资料图像

Is there an easy way to display the profile image from graph api in a react application

我正在寻找一种简单的方法来将图形 api 中的图像响应显示到 React 应用程序中。像这样 https://blogs.aaddevsup.xyz/2020/05/how-to-get-and-display-the-user-photo-with-graph-sdk-for-net-in-a-wpf-application/

当我尝试从 api 获取此内容时,不确定响应的格式以及如何将其转换并显示为图像?

MS Graph Docs - Using the binary data of the requested photo 有一些有用的注释。

这是从文档中提取的示例组件。请注意,我正在使用 Axios 使用 responseType: 'blob' 配置获取照片,并在我拥有它时进行渲染。

没有那个配置我无法让它工作。

import { useEffect, useState } from 'react';
import Axios from 'axios'

function App() {
  const [imageUrl, setImageUrl] = useState(null)
  useEffect(() => {
    Axios.get('https://graph.microsoft.com/v1.0/me/photo/$value', {
      headers: { 'Authorization': 'Bearer eyJ...' },
      responseType: 'blob'
    }).then(o => {
      const url = window.URL || window.webkitURL;
      const blobUrl = url.createObjectURL(o.data);
      setImageUrl(blobUrl)
    })
  }, [])
  return (
    <div className="App">
      {imageUrl && <img alt='my-user-avatar' src={imageUrl} />}
    </div>
  );
}

export default App;

仅供参考,您可能也对使用 MS Graph UI Toolkit for Reactjs 感兴趣,因为您似乎正在渲染用户个人资料卡片。

我尝试了不同的方法,最后这对我有用。

 useEffect(() => {
    const getPhoto = async () => {
      const graphEndpoint = "https://graph.microsoft.com/v1.0/me/photo/$value";

      const response = await axios(graphEndpoint, {
        headers: { Authorization: `Bearer ${sessionStorage.getItem("accesstoken")}` },
        responseType: "arraybuffer"
      });
      const avatar = Buffer.from(response.data, "binary").toString("base64");

      setPhotoData("data:image/jpeg;base64, " + avatar);
    };

    getPhoto();
  }, []);

我已经在没有为 api 请求导入新库的情况下工作了。希望下面的内容可以帮助任何被卡住的人。

我的失败是没有指定图像的尺寸。如果您不这样做,它将不会呈现。

useEffect(() => {
    GetProfilePicture()
}, [])

const [image, setImage] = useState()

const [isOk, setResponse] = useState()

const GetProfilePicture = async () => {

    const headers = new Headers();
    const bearer = 'Bearer ${props.token}';

    headers.append("Authorization", bearer);
    headers.append("Content-type", 'image/jpeg');

    const options = {
        method: "GET",
        headers: headers,
    };

    await fetch("https://graph.microsoft.com/v1.0/me/photo/$value", options)
    .then(response => {

        response.blob().then((data) => {
            const reader = new FileReader()
        
        reader.readAsDataURL(data)

        reader.onload = () => {
            const base64data = reader.result;
            
            setImage(base64data)
            setResponse(response.ok)
            
            }
        })
    })
} 

const ProfilePic = () => {
    if (isOk != false) {
        return (
            <Image style={{height: 90, width: 90}} key={image} source={{uri: image}}></Image>
        )
    } else {
        return (
            <Fragment></Fragment>
        )
    }
}