我正在尝试构建一个文件 uploader ,以便申请人可以上传特定职位的简历。我可以获得除文件上传输入之外的所有表单值。如何上传文件、序列化并将其存储在 mongodb 文档中(而不是服务器上的文件夹)?
模板:
<form id="applicants" enctype="multipart/form-data">
<label for="firstName">First Name:</label> <input type="text" id="first-name" /><br/>
<label for="lastName">Last Name:</label> <input type="text" id="last-name" /><br/>
<label for="email">Email:</label> <input type="text" id="email" /><br/>
<label for="phone">Phone:</label> <input type="text" id="phone" /><br/>
<br/>
<label for="resume">upload resume</label><input type="file" id="resume" /> | <a href="#employment"><< Back</a>
<input type="submit" value="submit resume" id="submit-resume">
</form>
查看:
var Marionette = require('backbone.marionette');
module.exports = itemView = Marionette.ItemView.extend({
initialize: function() {
// console.log("jobDetails itemView init");
this.listenTo(this.model, 'change', this.render);
// console.log("view's model ._id: ", this.model.attributes.get('_id'));
},
events: {
'click #submit-resume': 'save'
},
template: require('../../templates/job_post_details.hbs'),
save: function(e) {
e.preventDefault();
//console.log(this.model.attributes.get('_id'));
var newApplicant = {
firstName: this.$el.find('#first-name').val(),
lastName: this.$el.find('#last-name').val(),
phone: this.$el.find('#phone').val(),
email: this.$el.find('#email').val(),
jobPosts: [ this.model.attributes._id ],
resume: this.$('#resume').submit() // how to I obtain this data and serialize?
};
console.log("newApplicant: ", newApplicant);
window.App.controller.newApplicantCreate(newApplicant);
}
});
服务器端代码:
app.post('/api/applicants', job_post_applicants.add);
路由触发器在下面的 Controller 中添加功能:
add: function( req, res, next ) {
console.log("req: ", req);
console.log("res: ", res);
var newApplicant = new models.Applicant( req.body );
newApplicant.save( function( err, Applicant ) {
if (err) {
res.json({ error: 'Unable to create new Applicant.' });
} else {
res.json(Applicant);
console.log("added the Applicant: ", Applicant);
}
});
}
};
这是日志:
POST /api/applicants 200 37ms - 238b
added the Applicant: { __v: 0,
firstName: 'John',
lastName: 'Doe',
phone: '555.555.5555',
email: 'j_doe@email.com',
_id: 544eb24e9698b900000b5de9,
resume: {}, <=== how to I populate with serialized data?
createdAt: Mon Oct 27 2014 16:59:58 GMT-0400 (EDT),
jobPosts: [ 544995891887bd411b4f02ee ] }
最佳答案
您可以使用 FormData 对象并将其作为数据发送。
var form = new FormData();
form.append('firstName', this.$el.find('#first-name').val());
//... append all data
// Append resume file
form.append("resume", $("#resume")[0].files[0]);
并将其作为“multipart/form-data”内容类型发送。
关于jquery - 如何使用 Backbone.js、jQuery 和 Node.js 序列化要上传的表单文件,以便将其存储在 mongo 数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26596961/