upload-service.ts 944 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import multer from 'multer'
  2. import type { Options } from 'multer'
  3. import fs from 'fs'
  4. import { v4 } from 'uuid'
  5. import path from 'path'
  6. export const uploadService = () => {
  7. let folderPath = './imgs/'
  8. if (!fs.existsSync(folderPath)) {
  9. fs.mkdirSync(folderPath, { recursive: true })
  10. }
  11. const { limits: templateLimits }: Options = {
  12. limits: {
  13. files: 1,
  14. fieldNameSize: 400,
  15. fileSize: 80 * 1024 * 1024,
  16. },
  17. };
  18. const { filename }: multer.DiskStorageOptions = {
  19. filename: (_req, file, cb) => {
  20. const type = path.extname(file.originalname)
  21. cb(null, v4() + type)
  22. }
  23. }
  24. const generateHandler = () => {
  25. try {
  26. const options: Options = {
  27. limits: {
  28. ...templateLimits,
  29. },
  30. storage: multer.diskStorage({
  31. filename,
  32. destination: folderPath
  33. }),
  34. };
  35. return multer(options).single('imgs');
  36. } catch (e) {
  37. console.error('Upload error', e)
  38. throw e;
  39. }
  40. };
  41. return { generateHandler };
  42. };