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 文件上传

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值