1.安装multer
npm install multer
2.router/attachment.js 路由文件配置attachment/upload接口
// 1.引入express
const express = require("express");
const db = require("../util/db");
const upload_handler = require("../router_handler/attachment");
const multer = require("multer"); //导入multer模块
const path = require("path"); //导入path模块
const fs = require("fs"); //导入fs模块
// 判断路径 如果有就返回 如果没有对应文件夹就新建文件夹 返回最后路径
const mkdirs = (pathname, callback) => {
// 需要判断是否是绝对路径(避免不必要的 bug)
pathname = path.isAbsolute(pathname)
? pathname
: path.join(__dirname, pathname);
// 获取相对路径
pathname = path.relative(__dirname, pathname);
// path.sep 避免平台差异带来的 bug
const floders = pathname.split(path.sep);
let pre = ""; // 最终用来拼合的路径
floders.forEach((floder) => {
try {
// 没有异常,文件已经创建,提示用户该文件已经创建
const _stat = fs.statSync(path.join(__dirname, pre, floder));
const hasMkdir = _stat && _stat.isDirectory();
if (hasMkdir) {
callback; // && callback(`文件${floder}已经存在,不能重复创建,请重新创建!`)
}
} catch (err) {
// 抛出异常,文件不存在则创建文件
try {
// 避免父文件还没有创建的时候,先创建子文件所出现的意外 bug,这里选择同步创建文件
fs.mkdirSync(path.join(__dirname, pre, floder));
callback && callback(null);
} catch (error) {
callback && callback(error);
}
}
pre = path.join(pre, floder); // 路径拼合
});
};
// 获取今天日期 按日期存储到images文件夹中
const getDate = () => {
let today = new Date();
let y = today.getFullYear();
let m = addZero(today.getMonth() + 1);
let d = addZero(today.getDate());
return "" + y + m + d;
};
// 补0
const addZero = (num) => {
if (num < 10) {
return "0" + num;
} else {
return num;
}
};
// 配置multer上传文件的存储路径和文件名
var storage = multer.diskStorage({
// 配置文件上传后存储的路径
destination: function (req, file, cb) {
// 判断是否为图片类型
if (file.mimetype.indexOf("images")) {
// 生成今天日记 存放今天的图片
let today = getDate();
//拼接完整路径
let fallpath = path.join(__dirname, `../attachment/images/${today}`);
// 判断路径上的文件夹是否存在 不存在就创建
mkdirs(fallpath);
cb(null, fallpath);
} else {
// 不是图片就存到files文件夹中
cb(null, path.join(__dirname, "../attachment/files"));
}
},
// 配置文件上传后存储的文件名
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname));
},
});
// 将上传图片的multer配置完整
const upload = multer({
// 设置上传的文件存储位置和文件名(以上定义的multer.diskStorage)
storage: storage,
// 文件上传限制:单位字节
limits: { fileSize: 1024 * 1024 * 2 },
// 文件过滤:决定哪些文件可以上传,哪些文件跳过
fileFilter: function (req, file, cb) {
if (file.mimetype.startsWith("image")) {
cb(null, true); // 接收这个文件
} else {
cb(null, false); // 拒绝这个文件
}
},
});
// 2.创建路由实例对象 调用中间件解析file文件
var router = express.Router();
router.post("/attachment/upload", upload.single("file"), upload_handler.upload);
// 3.向外导出路由对象
module.exports = router;
3.router_handler/attachment.js路由处理函数文件注册处理函数
exports.upload = (req, res) => {
req.file.path = req.file.path.replace(/\\/g, "/"); //转移 \\ 为 /
let mypath = req.file.path.split("/attachment")[1];
let sendFile = {
name: req.file.originalname,
type: req.file.mimetype,
path: mypath,
};
res.send({
status: 200,
data: sendFile,
});
};
4.app.js将上传后的静态文件进行托管
app.use("/attachment", express.static("./attachment"));
5.前端调接口 传入上传成功后输入完整路径就能访问图片
如:
http:127.0.0.1/attachment/images/20230510/1683711649293.jpg