upload-service.ts 1.1 KB

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