node.js 文件上传_如何在Node.js中处理文件上传

node.js 文件上传

In how to upload a file using Fetch I explained how to upload a file to a server using Fetch.

在如何上传使用取文件我解释如何将文件上传到使用服务器获取 。

In this post I’m going to show you part 2: how to use Node.js, and in particular Express, to handle uploaded files.

在这篇文章中,我将向您展示第2部分:如何使用Node.js ,尤其是Express来处理上传的文件。

Install the express-fileupload npm module:

安装express-fileupload npm模块:

npm install express-fileupload

and add it to your middleware:

并将其添加到您的中间件中:

import fileupload from 'express-fileupload'

//or

const fileupload = require('express-fileupload')

After you created your Express app, add:

创建Express应用后,添加:

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

This is needed because otherwise the server can’t parse file uploads.

这是必需的,因为否则服务器将无法解析文件上传。

Now uploaded files are provided in req.files. If you forget to add that middleware, req.files would be undefined.

现在,在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 }))
  })
})

This is the smallest amount of code needed to handle files.

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

We call the mv property of the uploaded image. That is provided to us by the express-fileupload module. We move it to path and then we communicate the success (or an error!) back to the client.

我们称上传图片的mv属性。 这是由express-fileupload模块提供给我们的。 我们将其移至path ,然后将成功(或错误!)传达给客户端。

翻译自: https://flaviocopes.com/how-to-handle-file-uploads-node/

node.js 文件上传

你可能感兴趣的:(nodejs,vue,python,java,django,ViewUI)