multer不工作

时间:2018-04-24 06:54:44

标签: javascript node.js express multer

大家好我需要你的帮助我无法用multer修复我的问题,文件没有上传,req.file总是未定义。 这是我的代码

addProps.js

const multer = require('multer')
const upload = multer({ dest: 'public/imahe/' })

router.post('/add', isAuthenticated, upload.single('imahe'), (req, res, next) => {
      console.log(req.body)
      console.log(req.files)
      const member = req.user
      Members.findOne({})
      const props = new Property({
        pname: req.body.pname,
        ptype: req.body.ptype,
        price: req.body.price,
        pterm: req.body.pterm,
        location: req.body.location,
        description: req.body.description,
        gallery: req.body.imahe,
        owner: member._id
      })
      props.save( (err, props) => {
        if (err) {
          console.log('Unable to register your data: ' + err)
          throw err
        }
        console.log('Property Added Successful!')
        res.redirect('/dashboard')
      })
    })

addproperty.ejs

<% include header%>

  <div class="row">
    <form class="col s12" method="POST" action="/property/add">

      <div class="row">
        <div class="file-field input-field">
          <div class="btn">
            <span>File</span>
            <input type="file" name="imahe">
          </div>
          <div class="file-path-wrapper">
            <input class="file-path validate" type="text">
          </div>
        </div>
      </div>

      <button class="btn waves-effect waves-light" type="submit" name="action" value="submit">Submit
        <!-- <i class="material-icons right">send</i> -->
      </button>
    </form>
  </div>


  <% include foot%>

req.file或req.files总是在我身边返回undefined,我没有任何其他错误,我试图找到一些解决方案

这是我的标题

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')

    if (req.method === 'OPTIONS') {
        res.header('Access-Controll-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET')
        return res.status(200).json({})
    }
    next()
})

1 个答案:

答案 0 :(得分:0)

您需要将 enctype 设置为表单的 multipart / form-data

  

当您编写客户端代码时,您需要知道的是当表单包含任何元素时使用multipart / form-data。

希望以下代码段有用。

<form class="col s12" enctype='multipart/form-data' method="POST" action="/property/add" >

有关详细信息,请参阅this answer。