Skip to content

Instantly share code, notes, and snippets.

@Maxtermax
Created March 3, 2015 04:00
Show Gist options
  • Save Maxtermax/b2815837fc6a2a0b11f8 to your computer and use it in GitHub Desktop.
Save Maxtermax/b2815837fc6a2a0b11f8 to your computer and use it in GitHub Desktop.
//Uploading file directly on mongodb with gridfs-stream and multer express middleware
, multer = require('multer');
var dispatch = function(gfs) {
var stacks = [];//take all files
return multer({
onFileUploadStart:function(file){
stacks.push(gfs.createWriteStream({
filename:file.name,
mode:"w",
chunkSize:1024*4,
content_type:file.mimetype,
root:"fs",
metadata:{name:file.originalname}
}));//put writable stream at stacks array for handler
},
onFileUploadData:function(file,data) {
//this function is async for that we have to check with what file are working
stacks.forEach(function(stack) {
if(stack.name === file.name) stack.write(data);//writing in memory to mongodb
})
},
onFileUploadComplete:function(file) {
stacks.forEach(function(stack,index) {
//this function is async for that we have to check with what file are workin
if(stack.name === file.name) {
stack.end();
stacks.splice(index,1);//delete the files ready
}
})//stack
}
})
}//end dispatch files
app..use(dispatch(gfs))//middleware post and file request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment