1 回答

TA貢獻1824條經驗 獲得超6個贊
我會做的是使用存儲而不是數據庫來存儲文件。
例如 Amazon S3 或 Google 存儲桶。當您的用戶上傳圖片時,您將圖片本身發送到存儲桶,檢索 URL,然后將圖片 URL 保存在您的博客文檔中。
當您檢索圖像時,例如在您的博客“顯示”頁面上,您將 blog.imageUrl(或您對字段的任何稱呼)添加到 img 標簽中。
實現本身取決于您選擇的存儲提供商,但通常當您上傳內容時,您會得到提供商返回的承諾。一旦您解決返回的承諾,圖像 URL 通常可用。您先上傳,然后更新您的博客文檔。
就個人而言,我喜歡使用 firebase Firestore。(使用谷歌桶)這讓一切變得非常簡單。您安裝 firebase npm 模塊,并注冊一個新的 firebase 應用程序。然后,您可以創建一個用于上傳和存儲圖像的函數,如下所示:
const uploadImage = (blogId, image) => {
const storageRef = firebase.storage().ref(`${blogId}`); // Reference to bucket
storageRef.put(image)
.then(() =>{
storageRef.getDownloadURL()
.then((url) => {
console.log(url) // Gives you the URL to the uploaded image
// You can update or create your blog entry in mongodb here,
// and add the image url to the blog object.
});
});
}
添加回答
舉報