Sunday, 23 April 2017

How to connect mongoose schema with grid-fs file upload?

I am uploading file in mongo db collection using grid-fs. i am trying to connect the mongoose schema for user detail with the grid fs image file here is my code:

router.post('/', upload.any(), function(req, res, next) {

var path = req.files[0].path;

var imageName = req.files[0].originalname;

var imagepath = {};

imagepath['path'] = path;

imagepath['originalname'] = imageName;
    
    

console.log(path);

var dirname = require('path').dirname(__dirname);

var read_stream =  fs.createReadStream(dirname + '/' + path);

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

Grid.mongo = mongoose.mongo;

var gfs = Grid(connection.db);

var writeStream = gfs.createWriteStream({
    filename: imageName
});
read_stream.pipe(writeStream);

writeStream.on('close', function (file) {
    console.log(file.filename + 'Written To DB');
    fs.unlink(req.files[0].path);
});

res.send(req.files);});



via Awais Nawaz

No comments:

Post a Comment