繁体   English   中英

如何将来自 api 的响应转换为图像

[英]How can I convert the response coming from the api to image

我收到来自 api 的回复,如附图。 我想将此响应转换为图像。 我试图将其转换为 base64 字符串,但我也做不到。

响应图像

在此处输入图像描述

api是这样的:

          axios.get(`https://api.bamboohr.com/api/gateway.php/tadigital/v1/employees/2223/photo/large`, 
                { auth: {
                    username: 'xxxxxxxxxxxxxxxxx',
                    password: 'xxxxxxxxxxxxxxxxx'
                  }
                }
                ).then(resp => {
                  console.log(resp.data)
          });

我想要在 get 请求中不使用 responseType 的解决方案,因为 api 不接受响应类型。 我没有办法将其转换为图像

1 编码应为 base64 您可以在服务器或客户端上执行此操作。

2 原始数据应设置如下 -

    <img ng-src="data:image/*;base64,{{Raw Binary Data}}"/>

看起来服务器正在发送原始数据
您可以使用如下所示的 fetch 将其转换为 blob:

const res = await fetch(url);
const data = await res.blob();
const image = URL.createObjectURL(data);

Image设置为图像标签的src

我想要在 get 请求中不使用 responseType 的解决方案,因为 api 不接受响应类型。

responseType与服务器无关。 它告诉 Axios 如何处理预期的响应数据。 在这种情况下,您可以传递responseType: "blob" ,它可以传递给URL.createObjectURL()以创建可用作<img> src的 URL 。

const url = 'https://api.bamboohr.com/api/gateway.php/tadigital/v1/employees/2223/photo/large';
axios.get(url, {
  auth: {
    username: 'xxxxxxxxxxxxxxxxx',
    password: 'xxxxxxxxxxxxxxxxx',
  },
  responseType: 'blob',
}).then((resp) => {
  const img = document.createElement('img');
  img.src = URL.createObjectURL(resp.data);
  img.alt = 'employee photo';

  document.body.append(img);
});

 const url = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9Ii0xMS41IC0xMC4yMzE3NCAyMyAyMC40NjM0OCI+CiAgPHRpdGxlPlJlYWN0IExvZ288L3RpdGxlPgogIDxjaXJjbGUgY3g9IjAiIGN5PSIwIiByPSIyLjA1IiBmaWxsPSIjNjFkYWZiIi8+CiAgPGcgc3Ryb2tlPSIjNjFkYWZiIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiPgogICAgPGVsbGlwc2Ugcng9IjExIiByeT0iNC4yIi8+CiAgICA8ZWxsaXBzZSByeD0iMTEiIHJ5PSI0LjIiIHRyYW5zZm9ybT0icm90YXRlKDYwKSIvPgogICAgPGVsbGlwc2Ugcng9IjExIiByeT0iNC4yIiB0cmFuc2Zvcm09InJvdGF0ZSgxMjApIi8+CiAgPC9nPgo8L3N2Zz4K"; axios.get(url, { responseType: "blob", }).then((resp) => { const img = document.createElement("img"); img.src = URL.createObjectURL(resp.data); img.alt = "React icon"; document.body.append(img); }).catch((error) => { console.log(error); });
 <script crossorigin src="https://unpkg.com/axios@1/dist/axios.js"></script>

请注意,如果您不再需要 URL,则应调用URL.revokeObjectURL()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM