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

时间:2015-08-19 11:30:57

标签: node.js mongodb express gridfs

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

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

我尝试使用此处建议的busboy  Link

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

Youtube视频Link

youtube视频的结果正是我网站所需要的。我只需要知道在快递中不推荐使用body解析器的代码。

这是我的完整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:ID为55d5a3416aebd290131ca6d2的文件未打开以进行写入   C:\ MyProjects下\ gridFStesting \ node_modules \ mongodb的\ lib中\ utils.js:97       process.nextTick(function(){throw err;});                                           ^   TypeError:无法读取未定义的属性“stream”

这是我更新的代码:

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

错误只在某些时候发生。所以我不知道是什么导致了它。任何帮助,将不胜感激。

2 个答案:

答案 0 :(得分:0)

如果您使用gridfs-stream模块,则可以执行以下操作:

<%$ %>

答案 1 :(得分:0)

这解决了我的问题,我希望它可以帮助任何人在未来遇到这个问题。

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