multer req.file在上传时返回未定义

时间:2020-04-23 16:42:13

标签: node.js express multer

我正在制作带有身份验证的简单Express服务器,并且在制作表单以在注册时上传头像时遇到了麻烦。我希望用户能够在注册时输入用户名,电子邮件,密码和图像,并将图像存储在服务器中,并将相对路径存储在用户对象的属性中。有几篇关于类似问题的文章,但是我找不到我的代码出了什么问题。

路线:

const passport = require('passport')
const router = express.Router()
const { ensureLoggedIn, ensureLoggedOut } = require('connect-ensure-login')

const multer = require('multer')
const Image = require('./../models/Image.model')
const upload = multer({ dest: './../public/uploads', storage: './../public/uploads' })

  '/signup',
  upload.single('avatar'),
  ensureLoggedOut(),
  (req, res) => {

    console.log(req.file)

    const avatarPath = `/uploads/${req.file.filename}`

    Image.create({
      name: req.file.originalname,
      path: avatarPath
    })

    passport.authenticate('local-signup', {
      successRedirect: '/profile',
      failureRedirect: '/signup',
      failureFlash: true,
    })
  }
)

护照配置:

  'local-signup',
  new LocalStrategy(
    { passReqToCallback: true },
    (req, username, password, avatarPath, next) => {
      const { email } = req.body

      bcrypt
        .hash(password, 10)
        .then((hash) => {
          return User.create({
            username,
            email,
            password: hash,
            avatar: avatarPath,
          })
        })
        .then((user) => next(null, user))
        .catch((err) => next(err))
    }
  )
)

HTML:

        <div class="form-group">
          <label for="username">Username</label>
          <input type="text" name="username" class="form-control">
        </div>
        <div class="form-group">
          <label for="email">Email</label>
          <input type="text" name="email" class="form-control">
        </div>
        <div class="form-group">
          <label for="password">Password</label>
          <input type="password" name="password" class="form-control">
        </div>
        <div class="form-group">
          <label for="avatar">Avatar</label>
          <input type="file" name="avatar" class="form-control" enctype="multipart/form-data">
        </div>
        <button type="submit">Signup</button>
      </form>```



1 个答案:

答案 0 :(得分:0)

没关系,我已修复它。有几个错误-首先,我应该在表单开头定义enctype,例如;

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

然后,尽管我必须在POST路由上调用Multer来上传文件,但由Passport中间件来处理请求。如果我在那儿做console.log(req.file),就可以顺利进行。