我在哪里保存从节点js中的用户上传的图像

Where do I save images uploaded from users in node js

在节点js中,我在哪里保存用户上传的图片。我将博客保存在我的 mongodb 中,但是我应该在哪里保存用户上传的图像,因为此时我将图像保存在 base64 中,不推荐这样做。

请推荐一些存储用户图片的服务。

我会做的是使用存储而不是数据库来存储文件。
例如 Amazon S3 或 Google 存储桶。当您的用户上传图像时,您将图像本身发送到存储桶,检索 URL,然后将图像 URL 保存在您的博客文档中。

当您检索图像时,例如在您的博客“显示”页面上,您将 blog.imageUrl(或您对字段的任何称呼)添加到 img 标签中。

实现本身取决于您选择的存储提供商,但通常当您上传内容时,您会得到提供商返回的承诺。一旦您解决返回的承诺,图像 URL 通常可用。你先上传,然后更新你的博客文档。


就个人而言,我喜欢使用 firebase Firestore。 (使用 Google 桶)这让一切变得非常简单。您安装 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.
        });
    });
}