【问题标题】:Is there an easy way to display the profile image from graph api in a react application有没有一种简单的方法可以在反应应用程序中显示来自图形 api 的配置文件图像
【发布时间】:2021-11-06 03:03:14
【问题描述】:

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

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

【问题讨论】:

  • 到目前为止你尝试过什么?您收到 API 的响应了吗?如果是这样,它看起来像什么?如果不是how about checking out the docs
  • @Taxel ,我用从 api 获得的响应更新了问题,有没有办法可以转换我得到的响应并显示为图像?

标签: reactjs microsoft-graph-api


【解决方案1】:

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,因为您似乎正在呈现用户个人资料卡。

【讨论】:

  • 你能帮我解决这个问题吗stackoverflow.com/questions/69188265/…,我需要存储这个 blob 供以后在数据库中使用?怎么办?
  • 对于这种类型的存储,如果您的数据库引擎支持,您可以转换为 base 64 并存储或使用二进制存储。更好的解决方案是使用像 Azure Blob Storage 这样的 blob 存储,您可以使用 REST 调用它。在确定适合您的方案的解决方案之前,请进行适当的研究。
【解决方案2】:

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

 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();
  }, []);

【讨论】:

  • 如何将 accessToken 设置为会话存储?
猜你喜欢
  • 2010-11-09
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-09
相关资源
最近更新 更多