Last active
August 29, 2015 14:16
-
-
Save Maxtermax/335cd70727a2f31dc03f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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