登录
注册
node.js 学习社区
应用gridfs-stream模块上传图片到mongodb数据库

糖果花瓣流浪

2014-12-01 02:03

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

	}
 } 

原文引自:http://cnodejs.org/topic/51d249dcd44cbfa3040bd28a

回复 · 0

发表回复

你可以在回复中 @ 其他人