我正在尝试将图片上传到我的mongoDB,作为活动创建的一部分。这就是我到目前为止所做的:
事件架构:
var mongoose = require('mongoose');
var Event = new mongoose.Schema({
author: mongoose.Schema.Types.ObjectId,
authorName: String,
name: String,
priority: Number,
status: String,
date: Date,
img: { data: Buffer, contentType: String },
description: String,
joinedUsers: [{
username: {
type: String,
required: true,
index: { unique: true }
},
petitionStatus: String
}]
});
module.exports = mongoose.model('Event', Event);
我的玉观点:
form.form-signin(enctype="multipart/form-data",role='form',method='POST',action='/newEvent')
h2.form-signin-heading Create an Event
input.form-control(name='name', placeholder='Name of Event', required='', autofocus='')
textarea.form-control.event-description(placeholder='Please Enter a Description', name='description', required='')
input.form-control(name='date', type='date', required='')
input.form-control(name='img', type='file', required='')
button.btn.btn-lg.btn-primary.btn-block(type='submit') Create
快速API路线:
app.post('/newEvent',routes.createEvent);
我保存活动的方法
functions.createEvent = function(req, res){
var author;
var name = req.param('name');
var description = req.param('description');
var date = req.param('date');
UserSchema.findOne({ username: req.session.passport.user }, function(err, user) {
if (err) {
console.log(err);
res.status(404).json({status: err})
}
if (user) {
author = user.getID();
console.log(author);
var record = new EventSchema({
name: name,
description: description,
date:date,
author:author,
authorName: req.session.passport.user
});
record.save(function(err) {
if (err) {
console.log(err);
res.status(500).json({status: err});
} else {
res.redirect('/userEvents');
}
});
}
});
};
我已经表达了4因此不推荐使用bodyparser。如果有人能让我知道实现图片上传的好方法,我将不胜感激。
提前致谢
答案 0 :(得分:0)
body解析器,但是您可以使用busboy来配置应用程序
app.use(busboy());
然后可以从请求中访问该图像,如
exports.uploadDocument = function(req,res){
var fstream;
req.pipe(req.busboy);
var doc = new DocumentModel(); // just a example use your own
req.busboy.on('file',function(fieldname, file, filename, encoding, contentType){
doc.contentType = contentType;
doc.encoding= encoding;
doc.filename= filename;
file.on('data',function(data){
doc.content = data;
doc.size = data.length;
});
});