使用 GridFS 在 MongoDB 2015 年保存和加载图像

Saving and Loading Images in MongoDB 2015 using GridFS

我正在使用 nodeJS 和 mongoDB 创建数据输入表单。此表单的一部分要求用户上传图像。我找到了允许您执行此操作的资源,但现在此代码已弃用。

app.use(express.bodyParser((uploadDir: __dirname + '/public/uploads')));

我已经尝试按照此处的建议使用 busboy Link

这会将文件保存到上传目录中,但显然不会保存到 mongoDB。

YouTube 视频 Link

youtube 视频的结果正是我的网站所需要的。既然在 express 中不推荐使用主体解析器,我只需要知道使这成为可能的代码。

这是我的完整 nodeJS 代码:

var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var fs = require('fs');
var GridStore = mongo.GridStore;
var Server = mongo.Server;
var ObjectID = mongo.ObjectId;
var Db = mongo.Db;
var busboy = require('connect-busboy');

var server = new Server('localhost',27017,{auto_reconnect:true});
var db = new Db('exampleDb',server);

db.open(function(err,db){
    if(err)
    {
        console.log('Couldnt connect to mongo');
    }else{
        console.log('Connected to Mongo');
    }
});

    //app.use(express.static(__dirname +'/public'));
    app.use(express.static(path.join(__dirname, 'public')));
    //app.use(express.bodyParser((uploadDir: __dirname + '/public/uploads')));
   // app.use(bodyParser({uploadDir: __dirname + '/public/uploads'}));

app.use(busboy());

//app.use(bodyParser.urlencoded({
//    extended: true
//}));

app.get('/index.html', function (req, res) {
    res.sendFile( __dirname + "index.html" );
});

app.post('/upload',function(req,res){
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function (fieldname, file, filename) {
        console.log("Uploading: " + filename);
        fstream = fs.createWriteStream(__dirname + '/assets/uploads/' + filename);
        file.pipe(fstream);
        fstream.on('close', function () {
            res.redirect('back');
        });
    });
console.dir(req.file);
});



app.listen(3000);

更新:

我已经设法让它可以上传,但查看图片时我仍然遇到以下问题:

MongoError: file with id 55d5a3416aebd290131ca6d2 not opened for writing c:\MyProjects\gridFStesting\node_modules\mongodb\lib\utils.js:97 process.nextTick(function() { throw err; }); ^ TypeError: Cannot read property 'stream' of undefined

这是我更新后的代码:

    var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var fs = require('fs');
var GridStore = mongo.GridStore;
var Server = mongo.Server;
var ObjectID = mongo.ObjectId;
var Db = mongo.Db;
var busboy = require('connect-busboy');
var Grid = require('gridfs-stream');

var db = new mongo.Db('testing',new mongo.Server("127.0.0.1",27017));
var gfs = Grid(db,mongo);

db.open(function(err,db){
    if(err)
    {
        console.log('Couldnt connect to mongo');
    }else{
        console.log('Connected to Mongo');
    }
});

    //app.use(express.static(__dirname +'/public'));
    app.use(express.static(path.join(__dirname,'public')));
    //app.use(express.bodyParser((uploadDir: __dirname + '/public/uploads')));
   // app.use(bodyParser({uploadDir: __dirname + '/public/uploads'}));

app.use(busboy());

//app.use(bodyParser.urlencoded({
//    extended: true
//}));

app.get('/index.html', function (req, res) {
    res.sendFile( __dirname + "index.html" );
});

app.post('/upload',function(req,res){
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
        console.log('File [' + fieldname + ']: filename: ' + filename);
        var gfsstream = gfs.createWriteStream('pic');
        file.pipe(gfsstream).on('finish', function() {
            console.log('File [' + fieldname + '] Finished');
            console.log(gfsstream);
        });
    });
   // var gridStoreWrite = new GridStore(db,new ObjectID(),req.files.pic.name,"w",{chunkSize:1024,metadata:{}})
//console.dir('testing');
});

app.get('/image/:id',function(req,res){

    var id = req.params.id;
    var ObjectId = require('mongodb').ObjectID;
    var outPutFromDbFile = __dirname + '/public/uploads/' + id + '.png';
    var writeStream = fs.createWriteStream(outPutFromDbFile);

   // var BSON = require('mongodb').BSONPure;
   // var o_id = BSON.ObjectID.createFromHexString(id);

    var o_id = ObjectID(id);

    var gridStore = new GridStore(db,o_id,"r");
    gridStore.open(function (err,gridStore){
        if(err)
        {
            console.log('error' + err);
        }

        var readStream = gridStore.stream(true);
        readStream.on("end",function(){
           console.log('close was called');
            res.sendFile(outPutFromDbFile);
        });
        readStream.pipe(writeStream);
    });

});

app.listen(3000);

错误只在某些时候发生。所以我不知道是什么原因造成的。任何帮助,将不胜感激。

如果你使用gridfs-stream模块,你可以这样做:

var mongo = require('mongodb');
var Grid = require('gridfs-stream');

// create or use an existing mongodb-native db instance
var db = new mongo.Db('yourDatabaseName', new mongo.Server("127.0.0.1", 27017));
var gfs = Grid(db, mongo);

// ...

req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
  console.log('File [' + fieldname + ']: filename: ' + filename);
  var gfsstream = gfs.createWriteStream('/uploads');
  file.pipe(gfsstream).on('finish', function() {
    console.log('File [' + fieldname + '] Finished');
  });
});

这解决了我的问题我希望它能帮助将来遇到这个问题的任何人。

var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var fs = require('fs');
var GridStore = mongo.GridStore;
var Server = mongo.Server;
var ObjectID = mongo.ObjectId;
var Db = mongo.Db;
var busboy = require('connect-busboy');
var Grid = require('gridfs-stream');

var db = new mongo.Db('testing',new mongo.Server("127.0.0.1",27017));
var gfs = Grid(db,mongo);

db.open(function(err,db){
    if(err)
    {
        console.log('Couldnt connect to mongo');
    }else{
        console.log('Connected to Mongo');
    }
});

    //app.use(express.static(__dirname +'/public'));
    app.use(express.static(path.join(__dirname,'public')));
    //app.use(express.bodyParser((uploadDir: __dirname + '/public/uploads')));
   // app.use(bodyParser({uploadDir: __dirname + '/public/uploads'}));

app.use(busboy());

//app.use(bodyParser.urlencoded({
//    extended: true
//}));

app.get('/index.html', function (req, res) {
    res.sendFile( __dirname + "index.html" );
});

app.post('/upload',function(req,res){
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
        console.log('File [' + fieldname + ']: filename: ' + filename);
        var gfsstream = gfs.createWriteStream('pic');
        file.pipe(gfsstream).on('finish', function() {
            console.log('File [' + fieldname + '] Finished');
            console.log(gfsstream);
        });
    });
   // var gridStoreWrite = new GridStore(db,new ObjectID(),req.files.pic.name,"w",{chunkSize:1024,metadata:{}})
//console.dir('testing');
});

app.get('/image/:id',function(req,res){

    var id = req.params.id;
    var ObjectId = require('mongodb').ObjectID;
    var outPutFromDbFile = __dirname + '/public/uploads/' + id + '.png';
    var writeStream = fs.createWriteStream(outPutFromDbFile);

   // var BSON = require('mongodb').BSONPure;
   // var o_id = BSON.ObjectID.createFromHexString(id);

    var o_id = ObjectID(id);

    var gridStore = new GridStore(db,o_id,"r");
    gridStore.open(function (err,gridStore){
        if(err)
        {
            console.log('error' + err);
        }

        var readStream = gridStore.stream(true);
        readStream.on("end",function(){
           console.log('close was called');
            res.sendFile(outPutFromDbFile);
        });
        readStream.pipe(writeStream);
    });

});

app.listen(3000);