express-文件上传
- 安装 multer
1
npm i multer
封装 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
33const multer = require("multer");
const path = require("path");
const fs = require("fs");
const uploadPath = () => {
let upPath = path.join(__dirname, "../public/uploads");
if (!fs.existsSync(upPath)) {
fs.mkdirSync(upPath, { recursive: true });
}
return upPath;
};
const storage = multer.diskStorage({
destination: (req, file, callback) => {
if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
callback(null, uploadPath());
} else {
callback(new Error("Invalid file type"), null);
}
},
filename: (req, file, callback) => {
callback(null, file.originalname);
},
});
const upload = () => {
const multerConfig = multer({
storage,
});
return multerConfig.single("file");
};
module.exports = { upload, uploadPath };路由中使用
1
2
3
4
5
6
7
8
9
10
11
12
13const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const { upload, uploadPath } = require("../utils/upload");
router.post("/", upload(), function (req, res, next) {
if (req.file) {
res.send(uploadPath() + "/" + req.file.filename);
} else {
res.status(400).send("文件上传失败");
}
});