Angular2 - 如何使用表单数据submit [(ngModel)]上传文件并在MongoDB中保存引用

时间:2016-06-11 17:38:31

标签: node.js mongodb express angular

我有这个任务页面,想要将表单提交的文件上传到NodeJs express服务器。

router.route('/api/newtask')
    .post(function(req, res) {        
        var task = new Task();
        task.taskname = req.body.taskname;
        task.taskdesc = req.body.taskdesc;
        task.assignedto = req.body.assignedto;
        task.taskstatus = 'OPEN';
        task.save(function(err) {
            if (err)
                res.send(err);
            res.json({ message: 'Task created!' });
        });
  })

数据发布到expressjs服务器,如下所示

Server.ts

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var TaskSchema = new Schema({
  taskname: String,
  taskdesc: String,
  taskcreator:String,
  createddate: String,
  assignedto: String,
  taskstatus: String
 });

module.exports = mongoose.model('Task', TaskSchema);

mongodb的猫鼬mondel如下。

猫鼬模型

myObj

如何上传文件并将其与表单上的当前数据相关联?

1 个答案:

答案 0 :(得分:0)

请参阅此文https://www.npmjs.com/package/multer 你可以在服务器端使用multer,非常简单:

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file 
  // req.body will hold the text fields, if there were any 
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files 
  // req.body will contain the text fields, if there were any 
})

var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files 
  // 
  // e.g. 
  //  req.files['avatar'][0] -> File 
  //  req.files['gallery'] -> Array 
  // 
  // req.body will contain the text fields, if there were any 
})