应用gridfs-stream模块上传图片到mongodb数据库
发布于 6 年前 作者 banther 9176 次浏览 最后一次编辑是 3 年前

var mongoose = require(‘mongoose’); var Grid = require(‘gridfs-stream’); var async = require(‘async’); var gfs = Grid(mongoose.connection.db, mongoose.mongo); var GridFile = require(’…/…/models/gridfs’).GridFile;

var put_save = function(req, res) { var fnames = util.isArray(req.files.fname) ? req.files.fname : [req.files.fname]; async.map(fnames, process_file, function(err, results) { res.json({ ‘err’: err, ‘results’: results }) })

function process_file(fname, callback) {
    var gfs_options = {
        filename: fname.name,
        mode: 'w',
        content_type: fname.type,
        metadata: {
            'client': req.user.client.id,
            'user': req.user.id
        }
    };
    var writestream = gfs.createWriteStream(gfs_options);
    fs.createReadStream(fname.path).pipe(writestream);
    writestream.on('close', function(file) {
        fs.unlink(fname.path, function(err) {
            if (err) {
                return callback(err, null);
            };
            callback(null, file)
        });
    });

}

}

2 回复

这个包的作用式直接把文件以流的方式上传到mongo吗?

如果我要直接上传下载一个buffer数据呢,怎么操作????

回到顶部