在Nodejs和Express中上传Multer图像

时间:2017-03-03 11:56:42

标签: node.js image express upload multer

我几天来一直试图使用Multer上传图片。这是我得到了多远。我尝试了很多东西,似乎无法使它发挥作用。我不知道如何使用Multer以下面显示的格式在我的createUser函数中上传图像。

我的' server.js'文件:

var express = require('express');
var multer = require('multer');
var upload = multer({dest: 'uploads/'});
var router = require('./app/routes');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('client-sessions');
var DB_URI = "mongodb://localhost:27017/portfolio";
var app = express();
var path = require('path');
var fs = require('fs');
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(__dirname+ '/public'));
app.use(session({
  cookieName: 'session',
  secret: 'random_string_goes_here',
  duration: 30 * 60 * 1000,
  activeDuration: 5 * 60 * 1000,
}));

mongoose.connect(DB_URI);
app.use(router);

app.listen(8080, function(){
    console.log("server is listening on port 8080");
})

我的' routes.js'

var express = require('express');
var router = express.Router();
var projectController = require('./controllers/projectController');
var userController = require('./controllers/userController');
router.post('/regUser', userController.createUser);

我的' index.ejs'

<form class="form inv" method="POST" action="/regUser" id="reg_form">
          <h3 style="margin-bottom:40px;">Register</h3>
          <!-- <input type="file" name="file"/> -->
          <input type="text" class="form-control" name="name" placeholder="Name"/>
          <input type="text" class="form-control" name="username" placeholder="Username"/>
          <input type="text" class="form-control" name="email" placeholder="Email"/>
          <input type="password" class="form-control" name="password" placeholder="Password"/>
          <input type="file" name="userPhoto"/>
          <input type="submit" class="btn btn-default" value="Submit"/>
        </form>

我的userController.js

createUser: function(req, res){
//add code to create user AND upload image
}

2 个答案:

答案 0 :(得分:1)

有两个问题。

首先:您的表单没有设置enctype属性。文件提交工作需要enctype="multipart/form-data"

第二:您需要multer,但您没有使用它。添加此

app.use(multer({ dest: '/tmp/'}).single('userPhoto'))

(或使用其他方法(see documentation),例如.array().fields()

然后,您可以像createUser()一样访问该文件:

createUser: function(req, res){
    console.log(req.file); // this displays the userPhoto's properties
    fs.readFile(req.file.path, function (err, data) {
        // do something with the file data
    }
}

答案 1 :(得分:1)

我知道这是两个月前发布的,但对于那些遇到同样问题的人来说,

我认为你必须添加enctype =&#34; multipart / form-data&#34;到您的表格

<form action="url" method="post" enctype="multipart/form-data">

并且在您的router.route中,您必须添加upload.single()或upload.any()

router.post('/regUser', upload.single(), userController.createUser);