技術規范:React、Node、Express、MongoDB 到 Mongoose
我正在構建我的 GET API 以從我的 MongoDB 中檢索用戶影像。我目前有我的檔案包含影像值作為緩沖區(見截圖 #1)
GET API 回傳以下資料(見截圖 #2):

我的問題是如何將 MongoDB 回傳的 Buffer 值轉換為可用于顯示 Buffer 影像表示的變數型別。
我在網上找到了一些答案,例如以下代碼,但我不完全了解這些值是如何決議的。來源:https : //www.geeksforgeeks.org/upload-and-retrieve-image-on-mongodb-using-mongoose/
<img src="data:userPhoto/<%=image.img.contentType%>;base64,
<%=userPhoto.img.data.toString('base64')%>"/>
理想情況下,我希望使用從 API 回應中提取 Buffer 值,然后直接轉換為影像,然后將該影像傳遞給 html/react 組件。類似于下面的代碼:
const [userProfileImage, setUserProfileImage] = useState({});
//in API GET call
await axios({
method: 'get',
url,
}).then(function(response){
setUserProfileData(response.data[0].userPhoto.data);
}
//code to convert the local userProfileImage Buffer value to image, using Node Base64 maybe ??
//Not too sure what variable types I should pass into the Buffer.from
let imageValueConverted = Buffer.from(userProfileImage, '').toString('');
return (
<div>
<img src={imageValueConverted}/>
</div>
);
uj5u.com熱心網友回復:
嘗試像這樣設定影像:
const [userProfileImage, setUserProfileImage] = useState({});
//in API GET call
axios({
method: 'get',
url,
}).then(function(response){
let user = response.data[0];
setUserProfileImage(`data:${user.userPhotoExtensionType};base64, ${Buffer.from(user.userPhoto.data).toString('base64')}`);
});
并像這樣渲染它:
return (
<div>
<img src={userProfileImage}/>
</div>
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363712.html
上一篇:如何在onClick事件中通過FirstSecond和Lastname來提醒?
下一篇:無法安裝NPM
