UploadFaceVideo.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const API = require("../../lib/API")
  2. const { v4: uuidv4 } = require('uuid')
  3. const { BaseStdResponse } = require("../../BaseStdResponse")
  4. const multer = require('multer')
  5. const path = require('path')
  6. const fs = require('fs')
  7. const { url } = require("../../config.json")
  8. // 配置 Multer 存储选项
  9. const storage = multer.diskStorage({
  10. destination: (req, file, cb) => {
  11. const { student_num } = req.body
  12. if (!student_num) {
  13. return cb(new Error('缺少 student_num'))
  14. }
  15. const destPath = path.join('uploads', 'faces', student_num)
  16. fs.mkdirSync(destPath, { recursive: true }) // 确保目录存在
  17. cb(null, destPath)
  18. },
  19. filename: (req, file, cb) => {
  20. const randomName = uuidv4()
  21. cb(null, `${randomName}.webm`)
  22. }
  23. })
  24. // 限制文件类型为 webm
  25. const fileFilter = (req, file, cb) => {
  26. const extname = path.extname(file.originalname).toLowerCase() === ".webm"
  27. const mimetype = file.mimetype === "video/webm"
  28. if (extname && mimetype) {
  29. return cb(null, true)
  30. } else {
  31. cb(new Error('只允许上传 webm 格式的视频'))
  32. }
  33. }
  34. // 初始化 Multer
  35. const upload = multer({
  36. storage: storage,
  37. fileFilter: fileFilter,
  38. limits: { fileSize: 200 * 1024 * 1024 } // 最大 200MB
  39. }).single('upload')
  40. class UploadFaceVideo extends API {
  41. constructor() {
  42. super()
  43. this.noEncrypt()
  44. this.setMethod("POST")
  45. this.setPath("/UploadFaceVideo")
  46. }
  47. async onRequest(req, res) {
  48. upload(req, res, async (err) => {
  49. if (err) {
  50. this.logger.error(`视频上传失败!${err.stack || ''}`)
  51. return res.json({
  52. ...BaseStdResponse.ERR,
  53. msg: '视频上传失败!'
  54. })
  55. }
  56. const { student_num } = req.body
  57. if ([student_num].some(value => value === '' || value === null || value === undefined)) {
  58. return res.json({
  59. ...BaseStdResponse.MISSING_PARAMETER
  60. })
  61. }
  62. if (!req.file) {
  63. return res.json({
  64. ...BaseStdResponse.MISSING_PARAMETER,
  65. msg: '请上传 webm 视频文件'
  66. })
  67. }
  68. const videoPath = `${url}/uploads/faces/${student_num}/${req.file.filename}`
  69. res.json({
  70. ...BaseStdResponse.OK,
  71. data: {
  72. videoPath
  73. }
  74. })
  75. })
  76. }
  77. }
  78. module.exports.UploadFaceVideo = UploadFaceVideo