将数据插入MongoDB并使用enctype =" multipart / form-data"

时间:2018-02-19 10:00:24

标签: javascript node.js mongodb

我制作小型表单上传图片并将数据(名称,图片)插入mongoDB。 我使用multer并表达上传图片

我收到了一个错误。当我在HTML表单上添加enctype= multipart/form-data时。我的应用只能上传图片,但不能将数据(姓名,电子邮件)插入mongoDB。 当我删除它时,我的应用程序只插入数据但无法上传图像。

我在google上搜索过很多次但无法修复它。

我的服务器.js

var multer  =   require('multer');
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
const {ObjectID} = require("mongodb");
app.set('views',__dirname + '/views');
app.set('view engine','jade');

app.use(bodyParser());
app.use(methodOverride());
//app.use(app.router);
app.use(express.static(path.join(__dirname,'public')));

mongoose.connect('mongodb://localhost:27017/test');
var mySchema = new mongoose.Schema({
    _id : String,
    name: String,
    email : String
});

var user = mongoose.model('face',mySchema);

app.post('/new',function(req,res){
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });

    new user({
    _id   :  new ObjectID(),
    name : req.body.name,
    email : req.body.email
}).save(function(err,doc){
    if(err) res.json(err);
    else    res.send('Successfully inserted!');
});
});
var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.originalname);
  }
});
var upload = multer({ storage : storage}).single('userPhoto');
app.get('/',function(req,res){
      res.sendFile(__dirname + "/index.html");
});
app.listen(3001,function(){
    console.log("Working on port 3001");
});

我的HTML代码

<html>
  <head>
    <title>File upload Node.</title>
  </head>
  <body>
    <form action ="/new" method = "POST" enctype="multipart/form-data">
      <input type="file" name="userPhoto" /><br/>
  <label for="name">Name: </label>
   <input type="text" name = "name" /><br/>
  <label for="email">Email:</label>
   <input type = "text" name = "email" /><br/>

   <input type = "submit" />
   </form>
  </body>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
</html>

1 个答案:

答案 0 :(得分:0)

您在db中保存数据之前正在响应。首先在发送响应后上传图像并在db中保存数据。我更正了你的代码 -

var multer  =   require('multer');
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
const {ObjectID} = require("mongodb");
app.set('views',__dirname + '/views');
app.set('view engine','jade');

app.use(bodyParser());
app.use(methodOverride());
//app.use(app.router);
app.use(express.static(path.join(__dirname,'public')));

mongoose.connect('mongodb://localhost:27017/test');
var mySchema = new mongoose.Schema({
    _id : String,
    name: String,
    email : String
});

var user = mongoose.model('face',mySchema);

app.post('/new',function(req,res){
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
            new user({
             _id   :  new ObjectID(),
             name : req.body.name,
             email : req.body.email
           }).save(function(err,doc){
              if(err) res.json(err);
              else    res.send('Successfully inserted!');
           });
    });


});
var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.originalname);
  }
});
var upload = multer({ storage : storage}).single('userPhoto');
app.get('/',function(req,res){
      res.sendFile(__dirname + "/index.html");
});
app.listen(3001,function(){
    console.log("Working on port 3001");
});