Express 项目环境搭建 -- 10. 资源上传

处理文件上传要解析 multipart/form-data 请求体,Express 内置的中间件不覆盖这种类型,通常用 multer 来处理。

安装

1
npm install multer

基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const express = require("express");
const multer = require("multer");
const path = require("path");

// info 指定存储位置与文件名
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/");
},
filename: function (req, file, cb) {
const ext = path.extname(file.originalname);
cb(null, `${Date.now()}-${Math.round(Math.random() * 1e9)}${ext}`);
},
});

const upload = multer({
storage,
limits: {
fileSize: 5 * 1024 * 1024, // info 单个文件最大 5MB
},
fileFilter: function (req, file, cb) {
// info 只接受图片
if (file.mimetype.startsWith("image/")) {
cb(null, true);
} else {
cb(new Error("仅支持图片类型"));
}
},
});

app.post("/upload", upload.single("avatar"), function (req, res) {
// info 单文件挂载在 req.file
res.json({ file: req.file });
});

多文件上传

字段名相同的一组文件用 upload.array,不同字段用 upload.fields,解析结果挂载在 req.files:

1
2
3
app.post("/upload", upload.array("images", 5), function (req, res) {
res.json({ files: req.files });
});

错误处理

文件超过 limits.fileSize 或 fileFilter 拒绝时,multer 会抛错,交给错误处理中间件(见第 7 篇)。其中 LIMIT_FILE_SIZE 错误的 status 为 413,可以直接映射成「文件过大」的返回:

1
2
3
4
5
6
app.use(function (err, req, res, next) {
if (err.code === "LIMIT_FILE_SIZE") {
return res.status(413).json({ errcode: "40005", errmsg: "文件过大" });
}
next(err);
});

安全提醒

不要直接使用 file.originalname 拼接存储路径,否则可能覆盖任意文件;上面的示例用时间戳重命名,并保留扩展名。生产环境建议再限制允许的扩展名、把上传目录放在静态资源之外,避免被当作脚本执行。

参考链接

系列导航


Express 项目环境搭建 -- 10. 资源上传
https://bubao.github.io/posts/5f60f93e.html
作者
一念
发布于
2022年3月7日
许可协议