Home  >  Article  >  Web Front-end  >  How to use express to handle file upload in node project

How to use express to handle file upload in node project

青灯夜游
青灯夜游forward
2023-03-28 19:28:191662browse

怎么处理文件上传?下面本篇文章给大家介绍一下node项目中如何使用express来处理文件的上传,希望对大家有所帮助!

How to use express to handle file upload in node project

上传单个文件

我们可以使用 express 官方出品的第三方中间件 multer 来处理,先是安装:

npm i multer

然后我先放段比较完整的代码,之后解释:

const express = require('express')
const multer = require('multer')
const app = express()

const upload = multer({ dest: './uploads' })

app.post('/upload', upload.single('file'), (req, res) => {
  console.log(req.file)
  res.end('上传成功')
})

app.listen(4396, () => {
  console.log('服务器开启')
})

引入后的 multer 为一个函数,执行它得到 upload 对象,执行时可以传入配置,比如设置 dest (destination 的缩写) 为 './uploads',用于指定上传后的文件的存放位置:  【相关教程推荐:nodejs视频教程编程教学

const upload = multer({ dest: './uploads' })

由于对上传文件的处理并不是普遍需要的,所以对 upload 的使用是直接在匹配上传路径(我们定义为 '/upload')和方法(一般为 POST)的 app.post('/upload', ) 内,处理的是单个文件上传,所以使用 upload.single() 方法,传入的 'file'(自定义,也可以为其它名字) 为上传文件时的 key:

How to use express to handle file upload in node project

其执行会返回一个中间件函数,将得到的文件的数据赋值到 req.file,而文本字段的信息则会放在 req.body 中,并调用 next(),这样我们就可以接着注册一个中间件,打印查看文件信息,并向客户端返回请求结果 :

app.post('/upload', upload.single('file'), (req, res) => {
  console.log(req.body)
  console.log(req.file)
  res.end('上传成功')
})

发起上传请求后,打印得到的 req.body 如下:

[Object: null prototype] { name: 'jay' }

注意,如果请求的 body 使用 form-data 格式携带的数据里没有文件,而仅仅是一些文本字段,则 upload.single('file') 可以换成 upload.any()

打印得到的 req.file 如下:

{
  fieldname: 'file',
  originalname: 'How to use express to handle file upload in node project',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: './uploads',
  filename: '4c5781db70269d90cc57249e95a28894',
  path: 'uploads\\4c5781db70269d90cc57249e95a28894',
  size: 904454
}

并且文件会存储在 uploads 目录下:

How to use express to handle file upload in node project

可以看到,文件名为哈希值,且没有后缀,在 vscode 里无法直接查看图片:

How to use express to handle file upload in node project

但图片文件是可用的,使用 ps 是可以直接打开查看的。那如果想让文件存储时的文件名是添加后缀的,要怎么办呢?解决方案是在执行 const upload = multer() 时,传入的配置对象不再设置 dest 的值而改为设置 storage

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, './uploads')
  },
  filename(req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname)
  }
})
const upload = multer({ storage })

storage 对象由 multer.diskStorage() 生成,其内部传入对象,该对象有两个方法属性,它们都有 3 个参数,请求对象 req,文件信息 file,和一个回调函数 cb

  • destination 就是配置文件存储路径的,其作用等同于之前直接往 multer() 传入的 { dest: './uploads' },存储路径通过 cb 的第二个参数传入,cb 的第一个参数可以传 Error 对象或直接传 null
  • filename 就可以用来自定义文件名,因为 file.originalname 也就是上传的文件的原来的文件名,其是带有后缀的,所以我们在它前面加个时间戳来作为存储时的文件名。

现在再次发送上传文件请求,存储到 uploads 目录下的文件就有带后缀名了,可以直接在 vscode 打开查看:

How to use express to handle file upload in node project

上传多个文件

如果请求一次性上传多个文件,则只需要将 upload.single('file') 替换为 upload.array('files', 3) 即可,传入参数意为上传时文件的 key 为 files(自定义的,也可以是其它名字),并且限制最多上传 3 张图片,得到的文件信息可以在下一个中间件函数的 req.files 获取:

app.post('/upload', upload.array('files', 3), (req, res) => {
  console.log(req.files)
  res.end('上传成功')
})

当我们一次上传多个文件时:

How to use express to handle file upload in node project

打印 req.files 得到的就是个数组了:

[
  {
    fieldname: 'files',
    originalname: 'How to use express to handle file upload in node project',
    encoding: '7bit',
    mimetype: 'image/png',
    destination: './uploads',
    filename: '1676958850980-How to use express to handle file upload in node project',
    path: 'uploads\\1676958850980-How to use express to handle file upload in node project',
    size: 904454
  },
  {
    fieldname: 'files',
    originalname: 'qrcode.png',
    encoding: '7bit',
    mimetype: 'image/png',
    destination: './uploads',
    filename: '1676958850986-qrcode.png',
    path: 'uploads\\1676958850986-qrcode.png',
    size: 1076
  }
]

将文件部署为静态资源

可以使用内置的 express.static('./uploads') 中间件函数将存储上传文件的 uploads 目录设置为静态资源。然后传给 app.use()

app.use(express.static('./uploads'))

这样我们就可以直接通过浏览器查看上传得到的文件了,比如 uploads 有张图片如下:

How to use express to handle file upload in node project

只需要在浏览器输入 localhost:4396/1677031777791-How to use express to handle file upload in node project 即可查看。

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of How to use express to handle file upload in node project. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete