使用MongoDB,Express,Node.Js和GridFS-stream存储视频和图片文件

时间:2015-07-06 17:29:53

标签: javascript node.js mongodb express gridfs

我正在使用JavaScript(JQuery)创建单页面应用程序,并且需要存储大小超过16Mb的大型视频文件。我发现需要使用支持大文件的GridFS。因为我是MongoDB的新人,我不知道如何使用GridFS。有一些关于使用Node.js,MongoDB和Express创建应用程序的好教程,但无法找到任何描述如何将GridFS与MongoDB(非mongoose),Express和Node.js一起使用。我设法用上传文件的BSON文件大小限制为16MB。这就是我所拥有的:

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var Grid = require('gridfs-stream');

var db = monk('localhost:27017/elearning');
var gfs = Grid(db, mongo);

var routes = require('./routes/index');
var users = require('./routes/users');
var courses = require('./routes/courses');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Make our db accessible to our router
app.use(function(req,res,next){
  req.db = db;
  next();
});

app.use('/', routes);
app.use('/users', users);
app.use('/courses', courses);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

例如,课程文件如下:

var express = require('express');
var router = express.Router();

/* GET courses listing */
router.get('/courselist', function(req, res) {
    var db = req.db;
    var collection = db.get('courselist');
    collection.find({},{},function(e,docs){
        res.json(docs);
    })

});

/* POST courses data */
router.post('/courselist', function(req, res) {
    var db = req.db;
    var collection = db.get('courselist');
    collection.insert(req.body, function(err, result){
        res.send(
            (err === null) ? { msg: '' } : { msg: err }
        );
    });
});

/* Delete courses data */
router.delete('/courselist/:id', function(req, res) {
    var db = req.db;
    var collection = db.get('courselist');
    var userToDelete = req.params.id;
    collection.remove({ '_id' : userToDelete }, function(err) {
        res.send((err === null) ? { msg: '' } : { msg:'error: ' + err });
    });
});

module.exports = router;

我非常感谢你的帮助,如果你能告诉我如何编辑上面的文件以便利用GridFS并能够从我的网上学习数据库中获取,上传和删除视频和图片文件。

1 个答案:

答案 0 :(得分:3)

您可以使用gridfs-stream直接上传而不使用mongoose,只需:

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);

表示完整文件和正在运行的项目:

克隆节点作弊direct_upload_gridfs,运行node app后跟npm install express mongodb gridfs-stream

按照Node-Cheat Direct Upload via GridFS README.md

的步骤进行操作