Example code to use GridFS using mongoskin to upload file from form

320 views Asked by At

I am using mongoskin to connect mongodb in my project. Now I have requirement to use GridFs to upload images, audio etc. I have one HTML form to upload these files.

I tried to find out example code to upload file using mongoskin however could't find any good one.

Please help.

2

There are 2 answers

0
joy On

After spending many hours; I am able to use mongoskin to upload file to Gridfs. Not sure if this is perfect code however sharing it here because I couldn't find any single working code on searching Google :-)

https://github.com/dilipkumar2k6/gridfs-mongoskin


var DBModule = require('./DBModule.js');
var Grid = require('gridfs-stream');
var mongoskin = require('mongoskin');

//Upload file to server and also update the database
exports.uploadContent = function (req, res) {
    console.log('Calling uploadFile inside FileUploadService');
    req.pipe(req.busboy);
    req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        console.log('uploadFile  after busboy   fieldname: ' + fieldname + ", file : " + file + ", filename : " + filename);
        // make sure the db instance is open before passing into `Grid`
        var gfs = Grid(DBModule.db, mongoskin);
        //Get metadata var host = req.headers['host']; 
        var metadata = {contentType: mimetype};
        var writestream = gfs.createWriteStream({filename: filename, metadata: metadata});
        file.pipe(writestream);
        writestream.on('close', function (file) {
            // return URL to acces the uploaded content 
            var path = "contents/" + file._id;
            res.json({"path": path});
        });

        writestream.on('error', function (err) {
            log.error({err: err}, 'Failed to upload file to database');
            res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
            res.json({error: err});
        });
    });
};
//view file from database
exports.previewContent = function (req, res) {
    var contentId = new DBModule.BSON.ObjectID(req.params.contentid);
    console.log('Calling previewFile inside FileUploadService for content id ' + contentId);

    var gs = DBModule.db.gridStore(contentId, 'r');
    gs.read(function (err, data) {
        if (!err) {
            //res.setHeader('Content-Type', metadata.contentType);
            res.end(data);
        } else {
            log.error({err: err}, 'Failed to read the content for id ' + contentId);
            res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
            res.json({error: err});
        }
    });
};
0
Sàikät Dås On

Try this to store the data using gridfs (by default uses mongoskin). It worked for me.

var ObjectID = require('mongodb').ObjectID,
    GridStore = require('mongodb').GridStore;
    exports.saveMedia = function(db, media, next) {
        console.log(media)
        db.open(function (err, db) {
            // Create a file and open it
            var gridStore = new GridStore(db, new ObjectID(), "w");
            gridStore.open(function (err, gridStore) {
                // Write some content to the file
               gridStore.write(new Buffer(media), function (err, gridStore) {
                    // Flush the file to db
                    gridStore.close(function (err, fileData)
                        //returns filename
                        next(null, fileData)
                    });
                });
            });
        });
    }