Skip to content

Instantly share code, notes, and snippets.

@Maxtermax
Last active August 29, 2015 14:16
Show Gist options
  • Save Maxtermax/335cd70727a2f31dc03f to your computer and use it in GitHub Desktop.
Save Maxtermax/335cd70727a2f31dc03f to your computer and use it in GitHub Desktop.
//Uploading file directly on mongodb with gridfs-stream and multer express middleware
var multer = require('multer');
var express = require('express');
var mongoose = require('mongoose')
var Grid = require('gridfs-stream');
var conecction = function() {
var conn = mongoose.createConnection('localhost', 'fs_model', 27017).once('open', function() {
console.log('CONECTADO A fs_model');
})//end open connection
return Grid(conn.db, mongoose.mongo);
}
var gfs = connection();
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
app.post("/upload",function(req,res) {
res.send(req.files);
})
@Maxtermax
Copy link
Author

this code work to upload multiples o singles files but i am not sure if the memory overflow cause the writable stream dont use the event drain, for short the pipe functionality

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment