const API = require("../../lib/API") const { v4: uuidv4 } = require('uuid') const { BaseStdResponse } = require("../../BaseStdResponse") const multer = require('multer') const path = require('path') const fs = require('fs') const { url } = require("../../config.json") // 配置 Multer 存储选项 const storage = multer.diskStorage({ destination: (req, file, cb) => { const { student_num } = req.body if (!student_num) { return cb(new Error('缺少 student_num')) } const destPath = path.join('uploads', 'faces', student_num) fs.mkdirSync(destPath, { recursive: true }) // 确保目录存在 cb(null, destPath) }, filename: (req, file, cb) => { const randomName = uuidv4() cb(null, `${randomName}.webm`) } }) // 限制文件类型为 webm const fileFilter = (req, file, cb) => { const extname = path.extname(file.originalname).toLowerCase() === ".webm" const mimetype = file.mimetype === "video/webm" if (extname && mimetype) { return cb(null, true) } else { cb(new Error('只允许上传 webm 格式的视频')) } } // 初始化 Multer const upload = multer({ storage: storage, fileFilter: fileFilter, limits: { fileSize: 200 * 1024 * 1024 } // 最大 200MB }).single('upload') class UploadFaceVideo extends API { constructor() { super() this.noEncrypt() this.setMethod("POST") this.setPath("/UploadFaceVideo") } async onRequest(req, res) { upload(req, res, async (err) => { if (err) { this.logger.error(`视频上传失败!${err.stack || ''}`) return res.json({ ...BaseStdResponse.ERR, msg: '视频上传失败!' }) } const { student_num } = req.body if ([student_num].some(value => value === '' || value === null || value === undefined)) { return res.json({ ...BaseStdResponse.MISSING_PARAMETER }) } if (!req.file) { return res.json({ ...BaseStdResponse.MISSING_PARAMETER, msg: '请上传 webm 视频文件' }) } const videoPath = `${url}/uploads/faces/${student_num}/${req.file.filename}` res.json({ ...BaseStdResponse.OK, data: { videoPath } }) }) } } module.exports.UploadFaceVideo = UploadFaceVideo