我使用快速3.x和节点1.9与mongo和gridfs。要上传我使用gridfrom的文件,它在正常表单提交时工作正常但不能在基于ajax的表单提交中工作。我跟着几个网站但没有帮助。 http://www.davidpirek.com/blog/nodejs-html5-file-uploader
var gridform = require('gridform'),
mongoose = require('mongoose'),
mongo,
db,
app;
exports.upload_file = function(req, res){
var conn = mongoose.createConnection();
conn.open('localhost', 'employee', 27017, function (){
db = conn.db;
mongo = mongoose.mongo;
gridform.db = db;
gridform.mongo = mongo;
if ('POST' == req.method){
var form = gridform();
form.parse(req, function(err, fields, files) {
res.end("File ID:" + files.text.id);
});
}
});
}
以上代码适用于普通表单请求。但不是ajax表单请求。下面是我的客户端ajax调用。
jQuery("form#someform").change(function(event){
var formData = new FormData();
formData.append("filePath", document.getElementById("filePath").files[0]);
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function (evt) {
var obj = jQuery.parseJSON(evt.target.responseText);
window.location.hash = 'File';
MVC.message.show({text: obj.message, hideDealy: 2000});
}, false);
xhr.open("POST", "/upload_file");
xhr.send(formData);
});