使用MongoDB,Express,Node.Js和GridFS-stream来存储视频和图片文件 [英] Using MongoDB, Express, Node.Js and GridFS-stream for storing video and picture files

查看:257
本文介绍了使用MongoDB,Express,Node.Js和GridFS-stream来存储视频和图片文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript(JQuery)创建一个单页应用程序,需要存储大小超过16Mb的大型视频文件.我发现需要使用GridFS支持大文件.由于我是MongoDB的新成员,因此我不确定如何使用GridFS.有一些很好的教程,介绍如何使用Node.js,MongoDB和Express创建应用程序,但是找不到描述如何将GridFS与MongoDB(非Mongoose),Express和Node.js一起使用的任何教程.我设法放了一些东西来上传文件,其BSON文档大小限制为16MB.这就是我所拥有的:

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 files. As I am the new one to MongoDB I am not sure how to use GridFS. There are some good tutorials on creating applications using Node.js, MongoDB and Express but cant find any describing how to use GridFS with MongoDB (not mongoose), Express and Node.js. I managed to put up stuff for uploading files in the BSON-document size limit of 16MB. This is what I have:

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,并能够从我的学习数据库中获取,上传和删除视频和图片文件,我将非常感谢您的帮助.

I would be extremely grateful for your help, if you could tell how should I edit above files in order to utilize GridFS and be able to get, upload and delete video and picture files from my elearning database.

推荐答案

您可以使用

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

有关完整的文件和正在运行的项目:

克隆node-cheat direct_upload_gridfs ,运行后跟npm install express mongodb gridfs-stream.

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

OR

在Node-Cheat遵循婴儿步骤通过GridFS直接上传 README.md

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

这篇关于使用MongoDB,Express,Node.Js和GridFS-stream来存储视频和图片文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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