upload.module.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { Module } from '@nestjs/common';
  2. import { UploadService } from './upload.service';
  3. import { UploadController } from './upload.controller';
  4. import { MulterModule } from '@nestjs/platform-express';
  5. import { ConfigModule, ConfigService } from '@nestjs/config';
  6. import { KnowledgeBaseModule } from '../knowledge-base/knowledge-base.module'; // Import KnowledgeBaseModule
  7. import { KnowledgeGroupModule } from '../knowledge-group/knowledge-group.module';
  8. import * as multer from 'multer';
  9. import * as fs from 'fs';
  10. import * as path from 'path';
  11. import { UserModule } from '../user/user.module';
  12. @Module({
  13. imports: [
  14. KnowledgeBaseModule,
  15. KnowledgeGroupModule,
  16. UserModule,
  17. MulterModule.registerAsync({
  18. imports: [ConfigModule],
  19. useFactory: (configService: ConfigService) => {
  20. const uploadPath = configService.get<string>(
  21. 'UPLOAD_FILE_PATH',
  22. './uploads',
  23. ); // Get upload path from env varor use default './uploads' use
  24. // Ensure upload directory exists
  25. if (!fs.existsSync(uploadPath)) {
  26. fs.mkdirSync(uploadPath, { recursive: true });
  27. }
  28. // Get max file size from env var, default 100MB
  29. const maxFileSize = parseInt(
  30. configService.get<string>('MAX_FILE_SIZE', '104857600'), // 100MB in bytes
  31. );
  32. return {
  33. storage: multer.diskStorage({
  34. destination: (req: any, file, cb) => {
  35. const tenantId = req.user?.tenantId || 'default';
  36. const fullPath = path.join(uploadPath, tenantId);
  37. if (!fs.existsSync(fullPath)) {
  38. fs.mkdirSync(fullPath, { recursive: true });
  39. }
  40. cb(null, fullPath);
  41. },
  42. filename: (req, file, cb) => {
  43. // Fix Chinese filename garbling
  44. file.originalname = Buffer.from(
  45. file.originalname,
  46. 'latin1',
  47. ).toString('utf8');
  48. const uniqueSuffix =
  49. Date.now() + '-' + Math.round(Math.random() * 1e9);
  50. cb(
  51. null,
  52. `${file.fieldname}-${uniqueSuffix}${path.extname(file.originalname)}`,
  53. );
  54. },
  55. }),
  56. limits: {
  57. fileSize: maxFileSize, // File size limit
  58. },
  59. };
  60. },
  61. inject: [ConfigService],
  62. }),
  63. ],
  64. controllers: [UploadController],
  65. providers: [UploadService],
  66. })
  67. export class UploadModule { }