How can I upload files directly to Mongo GridFS using Formidable?

I am trying to transfer loading from Formidable directly to Mongo GridFS.

GridStore needs to be opened before any data can be recorded in the time required to open the store, too much data has not been analyzed and it fails.

How can I prepare the GridStore, then handle the incoming download?

function upload (request, response, next, options) { var form = new Formidable.IncomingForm(); var store = new Mongo.GridStore(options.mongoose.connection.db, new ObjectID, 'w+', { root: 'store', chunk_size: 1024 * 64 } ); form.onPart = function (part) { if(!part.filename){ form.handlePart(part); return; } part.on('data', function(buffer){ store.write(buffer); }); part.on('end', function() { store.close(); }); }; store.open( function (error, store) { form.parse(request); }); response.send(); } 

Also, the repository instance and repository opening should probably be placed inside onPart somehow.

Alex

+4
source share
2 answers

Since opening a GridStore file is asynchronous and formidable, you do not need to manually buffer the input stream formidables, waiting for the GridStore file to open. Since GridFS cannot be transferred to you, you will need to manually write each buffer piece to the GridStore after it is opened.

Just released gridform , which should do what you need.

https://github.com/aheckmann/gridform

+3
source

You can move the form processing code to the store.open , for example:

 function upload (request, response, next, options) { var store = new Mongo.GridStore(options.mongoose.connection.db, new ObjectID, 'w+', { root: 'store', chunk_size: 1024 * 64 } ); store.open( function (error, store) { var form = new Formidable.IncomingForm(); form.onPart = function (part) { if(!part.filename){ form.handlePart(part); return; } part.on('data', function(buffer){ store.write(buffer); }); part.on('end', function() { store.close(); }); }; form.parse(request); }); response.send(); } 
+1
source

Source: https://habr.com/ru/post/1410954/


All Articles