在 MERN 堆栈 Web 应用程序中存储图像的最佳方式 [英] Best way to store images in MERN stack web application

查看:39
本文介绍了在 MERN 堆栈 Web 应用程序中存储图像的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MERN 堆栈(MongoDB、Express Server、ReactJS 前端和 NodeJS 后端)构建一个 Web 应用程序,并且想知道一些从后端存储图像的好方法.

I am building a web application using the MERN stack (MongoDB, Express Server, ReactJS front end and NodeJS back end) and was wondering some good ways to store images from the back end.

过去,我直接从前端使用 Firebase 进行身份验证和存储.当我在 MongoDB 中处理我自己的用户身份验证模型时,是否仍然可以使用 firebase 存储,如果可以,它将来自前端还是后端.如果来自前端,我如何在没有 Firebase 身份验证的情况下保护它?

In the past, I have used Firebase for authentication and storage directly from the front end. As I am handling my own user authentication model in MongoDB, is it possible to still use firebase storage and if so would it be from the front end or back end. If it was from the front end, how would I secure it without having firebase authentication?

我读过的其他选项是使用 GridFS 将图像存储到 MongoDB 中或使用 Multer 存储在服务器上.

Other options I have read into are storing images into MongoDB using GridFS or storing on the server using Multer.

一旦我想到了解决方案,我就能够阅读文档并找出如何完成它.

Once I have a solution in mind, I will be able to read the docs and figure out how to get it done.

感谢任何建议.

推荐答案

我最终从 Firebase Admin SDK 实现了 Firebase Storage,并使用 Multer 将图像存储在内存中,直到我将它们加载到 Firebase.

I ended up implementing Firebase Storage from the Firebase Admin SDK and using Multer to store images in memory until I load them to Firebase.

https://firebase.google.com/docs/storage/admin/start

const uploader = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024,
  },
});


// @route   POST api/users/upload/avatar
// @desc    Upload a new avatar and save to storage
// @access  Private
router.post('/upload/avatar', [auth, uploader.single('image')], async (req, res, next) => {
  if (!req.file) {
    res.status(400).json({ msg: 'No file submitted.' });
    return;
  }

  try {
    const blob = firebase.bucket.file(req.file.originalname);
    const blobStream = blob.createWriteStream({
      gzip: true,
      resumable: false,
      metadata: {
        contentType: req.file.mimetype,
      },
    });

    blobStream.on('error', (err) => next(err));

    blobStream.on('finish', () => {
      publicUrl = `https://firebasestorage.googleapis.com/v0/b/${
        firebase.bucket.name
      }/o/${encodeURI(blob.name)}?alt=media`;

      res.status(200).json({
        photoURL: publicUrl,
      });

      User.findById(req.user.id).then((user) => {
        user.photoURL = publicUrl;
        user.save();
      });
    });

    blobStream.end(req.file.buffer);
  } catch (error) {
    console.error(error.message);
    res.status(500).send({ msg: 'A Server error occurred' });
  }
});

认为如果将来有人偶然发现此帖子,这可能会有所帮助.

Thought this might be helpful if someone stumbles upon this post in the future.

这篇关于在 MERN 堆栈 Web 应用程序中存储图像的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆