簡體   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