Using MongoDB, Express, Node.Js and GridFS-stream for storing video and picture files

后端 未结 2 1902
生来不讨喜
生来不讨喜 2021-01-15 09:32

I am creating a single page application using JavaScript(JQuery) and need to store large video files which size exceed 16Mb. I found that need to use GridFS supporting large

2条回答
  •  不要未来只要你来
    2021-01-15 09:54

    Very late but I found previous answer outdated. I'm posting this because this might help newbies like me. To run it, please follow previous answers guide. All credit goes to @ZeeshanHassanMemon.

    var express = require('express'),
    mongoose = require('mongoose'),
    Grid = require('gridfs-stream'),
    app = express();
    
    Grid.mongo = mongoose.mongo;
     conn = mongoose.createConnection('mongodb://localhost/node-cheat-db');
      conn.once('open', function () {
        var gfs = Grid(conn.db);
        app.set('gridfs', gfs);
        console.log('all set');
      });
    
    //POST http://localhost:3000/file
    app.post('/file', function (req, res) {
         var gridfs = app.get('gridfs');
        var writeStream = gridfs.createWriteStream({
            filename: 'file_name_here'
        });
        writeStream.on('close', function (file) {
            res.send(`File has been uploaded ${file._id}`);
        });
        req.pipe(writeStream);
    });
    
    //GET http://localhost:3000/file/[mongo_id_of_file_here]
    app.get('/file/:fileId', function (req, res) {
        var gridfs = app.get('gridfs');
        gridfs.createReadStream({
            _id: req.params.fileId // or provide filename: 'file_name_here'
        }).pipe(res);
    });
    
    app.listen(process.env.PORT || 3000);
    

提交回复
热议问题