Express中使用间件Multer保存图片文件(示例)
# 安装multer
npm i multer
1
# 引入依赖
const path = require("path");
const multer = require("multer");
1
2
2
# 代码示例
前端代码
const newFormData = new FormData();
newFormData.append("file", file);
axios.post("/notez/file/upload", newFormData, {
headers: {},
}).then((res) => {
if (res.data.code == 200) {
console.log(res.data);
}
});
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
后端代码
let storage = multer.diskStorage({
//设置 上传图片服务器位置
destination: path.resolve(__dirname, "./public/img"),
//设置 上传文件保存的文件名
filename: function (req, file, cb) {
// 获取后缀扩展
let extName = path.extname(file.originalname); //.jpg
// 获取名称
let fileName = Date.now();
// console.log(fileName + extName); //12423543465.jpg
cb(null, fileName + extName);
},
});
let fileFilter = function (req, file, cb) {
let acceptableMime = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
// 限制类型
// null是固定写法
if (acceptableMime.indexOf(file.mimetype) !== -1) {
cb(null, true); // 通过上传
} else {
cb(null, false); // 禁止上传
}
};
let limits = {
fileSize: "2MB", //设置限制(可选)
};
const imageUploader = multer({ fileFilter, storage, limits }).single("file"); //文件上传预定 name 或者 字段
router.post("/file/upload", imageUploader, (req, res, next) => {
let username = req.headers["username"];
let password = req.headers["password"];
// console.log(req.file);
if (config.login.username == username && config.login.password == password) {
try {
let name = path.basename(req.file.path);
res.json({
message: "操作成功!",
code: 200,
url: "/img/" + name,
name,
});
} catch (error) {
console.log(error);
res.json({ message: "操作失败!", code: 500 });
}
} else {
res.json({ message: "请登录后再试!", code: 400 });
}
});
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
上次更新: 2024/01/30, 00:35:17
- 01
- Node与GLIBC_2.27不兼容解决方案08-19
- 02
- Git清空本地文件跟踪缓存08-13