upload.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import multer from '@koa/multer';
  2. import fs from 'fs';
  3. import path from 'path';
  4. /**
  5. * 创建 multer 实例
  6. * @param {Object} options - multer 配置选项
  7. * @returns {Object} multer 实例
  8. */
  9. export const createMulter = (options = {}) => {
  10. // 默认配置
  11. const defaultOptions = {
  12. dest: './public/uploads/',
  13. limits: {
  14. fileSize: 2 * 1024 * 1024, // 2MB
  15. }
  16. };
  17. // 合并选项
  18. const mergedOptions = { ...defaultOptions, ...options };
  19. // 如果没有指定 storage,使用 diskStorage
  20. if (!mergedOptions.storage) {
  21. const uploadDir = mergedOptions.dest;
  22. // 确保上传目录存在
  23. if (!fs.existsSync(uploadDir)) {
  24. fs.mkdirSync(uploadDir, { recursive: true });
  25. }
  26. mergedOptions.storage = multer.diskStorage({
  27. destination: function (req, file, cb) {
  28. cb(null, uploadDir);
  29. },
  30. filename: function (req, file, cb) {
  31. const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
  32. cb(null, uniqueSuffix + path.extname(file.originalname));
  33. }
  34. });
  35. }
  36. return multer(mergedOptions);
  37. };
  38. // 默认 multer 实例
  39. const defaultMulter = createMulter();
  40. /**
  41. * 单文件上传中间件
  42. * @param {string} fieldName - 表单字段名
  43. * @param {Object} options - multer 配置选项
  44. * @returns {Function} koa 中间件
  45. */
  46. export const uploadSingle = (fieldName = 'file', options = {}) => {
  47. if (Object.keys(options).length === 0) {
  48. return defaultMulter.single(fieldName);
  49. }
  50. return createMulter(options).single(fieldName);
  51. };
  52. /**
  53. * 多文件上传中间件
  54. * @param {string} fieldName - 表单字段名
  55. * @param {number} maxCount - 最大文件数
  56. * @param {Object} options - multer 配置选项
  57. * @returns {Function} koa 中间件
  58. */
  59. export const uploadMultiple = (fieldName = 'files', maxCount = 5, options = {}) => {
  60. if (Object.keys(options).length === 0) {
  61. return defaultMulter.array(fieldName, maxCount);
  62. }
  63. return createMulter(options).array(fieldName, maxCount);
  64. };