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

吃可爱长大的小学妹 提交于 2019-12-01 11:49:51

You can do direct uploading without using mongoose using gridfs-stream as simple as:

var express = require('express'),
    mongo = require('mongodb'),
    Grid = require('gridfs-stream'),
    db = new mongo.Db('node-cheat-db', new mongo.Server("localhost", 27017)),
    gfs = Grid(db, mongo),
    app = express();

db.open(function (err) {
    if (err) return handleError(err);
    var gfs = Grid(db, mongo);
    console.log('All set! Start uploading :)');
});

//POST http://localhost:3000/file
app.post('/file', function (req, res) {
    var writeStream = gfs.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) {
    gfs.createReadStream({
        _id: req.params.fileId // or provide filename: 'file_name_here'
    }).pipe(res);
});

app.listen(process.env.PORT || 3000);

for complete files and running project:

Clone node-cheat direct_upload_gridfs, run node app followed by npm install express mongodb gridfs-stream.

OR

Follow baby steps at Node-Cheat Direct Upload via GridFS README.md

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!