Multer Upload Single在React.js中不起作用

时间:2019-03-05 11:51:10

标签: node.js reactjs multer

我尝试了多个在线资源将文件上传到本地计算机上的目标位置。此控制台显示文件已上传,但在目标文件夹中看不到该文件。这是我的server.js代码:

const app = express()
app.use(bodyParser())
app.set('view engine', 'hbs')
app.use(express.static(__dirname + '/public'))
app.set('views', __dirname + '/views')
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

app.get('/', (req, res) => {
  res.render('index.hbs')
})

app.listen(port, () => {
  console.log(`App is live on port ${port}`)
})

app.post('/upload', upload.single('myFile'), (req, res, next) => {

  console.log('called')
  console.log(req.body.myFile)

  if (req.body.myFile) {
    console.log('Uploading file...')
    var filename = req.body.myFile

    var uploadStatus = 'File Uploaded Successfully'
  } else {
    console.log('No File Uploaded')
    console.log('======================== SESSION END ========================')
    var filename = 'FILE NOT UPLOADED'
    var uploadStatus = 'File Upload Failed'
  }

  /* ===== Add the function to save filename to database ===== */

  res.render('index.hbs', { status: uploadStatus, filename: `Name Of File: ${filename}` })
})

这是我的index.hbs文件:

<form action="/upload"  method="POST">
    <input type="file" name="myFile"  required />
    <input type="submit" value="Upload"  />
</form>

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这里的问题出在您的健身中心。 表单缺少以下属性:enctype="multipart/form-data"

PS:req.body应该包含额外的数据(例如文本字段),要输出文件,您应该检查req.file

所有内容都在文档中:https://github.com/expressjs/multer#readme