1. 代码如下
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const imgPath = "/keep/";
let updateBaseUrl =
process.env.NODE_ENV === "production"
? "https://xxx.xxxx.com"
: "http://127.0.0.1:8080";
let imgDirPath =
process.env.NODE_ENV === "production"
? "服务器上传路径" + imgPath
: "本地上传路径" + imgPath;
fs.promises.mkdir(imgDirPath, {
recursive: true }).catch(console.error);
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, imgDirPath),
filename: (req, file, cb) => {
const {
name, ext } = path.parse(file.originalname);
const uniqueSuffix = `${
Date.now()}-${
Math.round(Math.random() * 1e9)}`;
cb(null, `${
name}-${
uniqueSuffix}${
ext}`);
},
});
const multerConfig = multer({
storage,
limits: {
fileSize: 10 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
const allowedMimeTypes = ["image/png", "image/jpeg", "image/jpg"];
cb(null, allowedMimeTypes.includes(file.mimetype));
},
});
exports.upload = (req, res) => {
console.log("上传接口 自定义方法触发");
return new Promise((resolve, reject) => {
multerConfig.single("file")(req, res, (err) => {
if (err) {
console.log("获取资源失败 抛出错误");
console.error("Error occurred during upload:", err.message);
return reject(
new Error("Error occurred during upload: " + err.message)
);
}
console.log("获取资源成功 拼接url");
console.log("File uploaded successfully:", req.file.filename);
resolve(`${
updateBaseUrl}/common/image/${
req.file.filename}`);
});
});
};
exports.getFile = (req, res) => {
return new Promise((resolve, reject) => {
const filePath = path.join(imgDirPath, req.params.filename);
fs.promises
.access(filePath, fs.constants.F_OK)
.then(() => resolve(filePath))
.catch(() => {
console.error("File not found:", req.params.filename);
reject(new Error("File not found"));
});
});
};