我上傳了一張圖片。現在,我有一個下載 API,可以將此影像作為資料提供給我。回應如下所示:

回應的標頭是這樣的:

現在的問題是我想在網頁上使用 img 標簽或任何其他可能的 react js 來顯示這個影像。將內容傳遞給 src attr 沒有顯示任何內容。有沒有人有任何想法?有沒有可能的方法?
uj5u.com熱心網友回復:
您應該能夠使用 FileReader 將回應轉換為可在 src 屬性中使用的 base64 格式:
// Request was successful, get image blob
const blob = await response.blob()
// Convert the blob to base64
const reader = new FileReader()
reader.readAsDataURL(blob)
// Get the converted image and set it where needed
reader.onloadend = () => {
const base64Image = reader.result
// Set the image to the src of the image tag or setState as you need
}
uj5u.com熱心網友回復:
除了上面的答案之外,這也對我有用:
const fetchImage = async () => {
fetch(apiUrl, {
method: 'get',
headers: new Headers({
Authorization: `Bearer ${getCookie('accessToken')}`,
}),
})
.then((response) => response.blob())
.then((myBlob) => {
const objectURL = URL.createObjectURL(myBlob);
setImageUrl(objectURL);
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/464590.html
標籤:javascript 反应 图片 api
上一篇:NodeJS應用程式不上傳檔案
下一篇:“物件”型別上不存在屬性“名字”
