如何在Node.js中处理文件上传的问题

72 阅读1分钟

如何使用Node.js,特别是Express来处理上传的文件

发表于2019年10月31日,最后更新于2019年11月12日

如何使用Fetch上传文件中,我解释了如何使用Fetch向服务器上传文件。

在这篇文章中,我将向你展示第二部分:如何使用Node.js,特别是Express来处理上传文件。

安装 express-fileuploadnpm模块。

npm install express-fileupload

并将其添加到你的中间件。

import fileupload from 'express-fileupload'

//or

const fileupload = require('express-fileupload')

在你创建了你的Express应用后,添加。

app.use(
  fileupload(),
  //...

这是需要的,因为否则服务器不能解析文件的上传。

现在,上传的文件被提供在req.files 。如果你忘记添加该中间件,req.files 将成为undefined

app.post('/saveImage', (req, res) => {
  const image = req.files.myFile
  const path = __dirname + '/images/' + image.name


  image.mv(path, (error) => {
    if (error) {
      console.error(error)
      res.writeHead(500, {
        'Content-Type': 'application/json'
      })
      res.end(JSON.stringify({ status: 'error', message: error }))
      return
    }

    res.writeHead(200, {
      'Content-Type': 'application/json'
    })
    res.end(JSON.stringify({ status: 'success', path: '/images/' + image.name }))
  })
})

这是处理文件所需的最小的代码量。

我们调用上传图片的mv 属性。那是由express-fileupload 模块提供给我们的。我们把它移到path ,然后我们把成功(或错误!)传回给客户端。