Skip to content

Instantly share code, notes, and snippets.

@saranyan
Created April 25, 2016 00:12
Show Gist options
  • Save saranyan/002a2ceff7f7434d834c9d820b5725eb to your computer and use it in GitHub Desktop.
Save saranyan/002a2ceff7f7434d834c9d820b5725eb to your computer and use it in GitHub Desktop.
Save file to Grid-fs
var conn = mongoose.connection;
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
//grid-fs
var gfs = Grid(conn.db);
//create a file by filename
app.post('/foo/file', auth, function(req, res) {
//so, this is a complete workaround to get a
//non-form based multipart working
//the problem here is that - mutlipart modules like multle does not
//work cleanly for a non-form upload.
//Went for the deprecated body-parser and the inbuilt multipart express
//provides. it does not preserve file name in the req.body, so a custom header
//with the filename works for now.
//
headers = JSON.stringify(req.headers)
//console.log(req.headers["x_filename"])
var options = {filename : req.headers["x_filename"]}
gfs.exist(options, function (err, found) {
if (err) throw err;
if (!found){
var writestream = gfs.createWriteStream({
filename: req.headers["x_filename"]
});
req.pipe(writestream);
writestream.on('finish', function (file) {
console.log("Model updated into grid-db");
res.send("Success!");
});
}
else {
res.send('File exists')
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment