我正在尝试将文件上传直接流式传输到 Mongo。似乎 gridform ( https://github.com/aheckmann/gridform ) 是一个很好的解决方案。
我已经在使用 express 框架并且喜欢它正在做的事情所以想继续使用它,但是 gridform 的使用示例似乎是基于没有 express 的本机 http 服务器。
我发现 express.bodyParser() 与 gridform 冲突,所以不是:
app.use(express.bodyParser()); 我正在使用 app.use(express.json()); app.use(express.urlencoded());
让我感到困惑的那部分是我现在如何在我的路线中使用网格形式。app.post('/data/AddPropertyImage', db.addPropertyImage);
export.addPropertyImage = function(req, res){ ??? }
尽我所能尝试我似乎无法从 var form = gridform(); 这个断言一直失败。assert(form instanceof formidable.IncomingForm);
这是完整的代码段。
exports.addPropertyImage = function(req, res){
var mongo = require('mongodb')
var formidable = require('formidable');
var assert = require('assert');
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var MongoDb = new Db('test', new Server('localhost', 27017), {w: 1});
MongoDb.open(function(err, db) {
var gridform = require('gridform');
gridform.db = db;
gridform.mongo = mongo;
var form = gridform();
// returns a custom IncomingForm
assert(form instanceof formidable.IncomingForm);
// this returns AssertionError: false == true
});
res.send('test');
};
编辑...
如下所述,我需要使用强大的特定版本 var formidable = require('gridform/node_modules/formidable');
断言现在通过了,但 form.parse() 似乎永远不会触发。所以 console.log('start parse'); 下面的线永远不会被击中。
console.log('start');
var mongo = require('mongodb')
//var formidable = require('formidable');
var formidable = require('gridform/node_modules/formidable');
var gridfsStream = require('gridform/node_modules/gridfs-stream');
console.log(gridfsStream);
var assert = require('assert');
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var MongoDb = new Db('test', new Server('localhost', 27017), {w: 1});
console.log('mongo open');
MongoDb.open(function(err, db) {
var gridform = require('gridform');
gridform.db = db;
gridform.mongo = mongo;
var form = gridform();
// returns a custom IncomingForm
assert(form instanceof formidable.IncomingForm);
// this returns AssertionError: false == true
console.log('assert passed');
// optionally store per-file metadata
form.on('fileBegin', function (name, file) {
console.log('mmmeta');
file.metadata = 'so meta'
})
// parse normally
form.parse(req, function (err, fields, files) {
console.log('start parse');
// use files and fields as you do today
var file = files.inpFile1;
console.log(file);
file.name // the uploaded file name
file.type // file type per [mime](https://github.com/bentomas/node-mime)
file.size // uploaded file size (file length in GridFS) named "size" for compatibility
file.path // same as file.name. included for compatibility
file.lastModified // included for compatibility
// files contain additional gridfs info
file.root // the root of the files collection used in MongoDB ('fs' here means the full collection in mongo is named 'fs.files')
file.id // the ObjectId for this file
});
});
res.send('test');