【问题标题】:Do you need to save a file locally before sending it to a mongo db?在将文件发送到 mongodb 之前,是否需要在本地保存文件?
【发布时间】:2020-07-04 19:28:50
【问题描述】:

我正在学习如何通过快速服务器将图像从我的 React 网站上传到我的 Mongo 数据库。在我读过的每个教程中,作者在将文件发送到 Mongo 数据库之前,将文件本地保存在 express 服务器中。有没有办法避免将文件保存在本地变量中,然后上传到数据库中?

这里是我指的教程:

https://www.positronx.io/react-file-upload-tutorial-with-node-express-and-multer/

https://medium.com/ecmastack/uploading-files-with-react-js-and-node-js-e7e6b707f4ef

感谢您的帮助。

【问题讨论】:

    标签: javascript reactjs express multer


    【解决方案1】:

    我猜 GridFS API 会对你有所帮助。它说:

    你可以 .pipe() 直接从文件流到 MongoDB

    这是根据文档的示例:

    const assert = require('assert');
    const fs = require('fs');
    const mongodb = require('mongodb');
    
    const uri = 'mongodb://localhost:27017';
    const dbName = 'test';
    
    mongodb.MongoClient.connect(uri, function(error, client) {
      assert.ifError(error);
    
      const db = client.db(dbName);
    
      var bucket = new mongodb.GridFSBucket(db);
    
      fs.createReadStream('./meistersinger.mp3').
        pipe(bucket.openUploadStream('meistersinger.mp3')).
        on('error', function(error) {
          assert.ifError(error);
        }).
        on('finish', function() {
          console.log('done!');
          process.exit(0);
        });
    });
    

    文档链接:https://mongodb.github.io/node-mongodb-native/3.0/tutorials/gridfs/streaming/

    希望有帮助!

    【讨论】:

      【解决方案2】:

      是的,您想将文件存储在本地。我使用了 NFS 服务器 (FreeNas) 并将其安装到该本地文件夹。

      因此,当我将文件保存到该位置时,它存储在其他 NFS 服务器上。然后我将该图像位置作为响应发送回响应,然后将该位置保存在 Mongodb 中。

      示例 uploads.js

      
      router.post('/', auth, async (req, res) => {
          let CurrentDate = moment().unix();
          if (req.files.file === null) {
              return res.status(400).json({ msg: 'no file uploaded' });
          }
      
          let user = await User.findById(req.user.id).select('-password');
          let file = req.files.file;
      
          file.name = CurrentDate + user._id + '.jpg';
      
      
          file.mv(`./client/public/uploads/${file.name}`, (err) => {
              if (err) {
                  console.error(err);
                  return res.status(500).send(err);
              }
      
      
              res.json({ fileName: file.name, filePath: `/uploads/${file.name}`});
          });
      });
      

      这就是mongodb条目的样子

      image:"/uploads/15951066675f1365239d46882312332d20.jpg"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 2021-09-29
        • 1970-01-01
        • 2015-01-14
        相关资源
        最近更新 更多