Files
delivery-desk/api/upload.ts

52 lines
1.2 KiB
TypeScript
Raw Normal View History

/**
* multer
*/
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const uploadsDir = path.resolve(__dirname, '..', 'uploads');
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
const storage = multer.diskStorage({
destination: (_req, _file, cb) => {
cb(null, uploadsDir);
},
filename: (_req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase() || '.jpg';
const unique = `${Date.now()}_${Math.round(Math.random() * 1e6)}${ext}`;
cb(null, unique);
},
});
const allowedMime = new Set([
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/avif',
]);
export const upload = multer({
storage,
limits: {
fileSize: 20 * 1024 * 1024, // 20MB / 单图
files: 30, // 最多 30 张
},
fileFilter: (_req, file, cb) => {
if (allowedMime.has(file.mimetype)) {
cb(null, true);
} else {
cb(new Error(`不支持的文件类型: ${file.mimetype}`));
}
},
});
export const UPLOADS_DIR = uploadsDir;