@nestjs/platform-express#FileInterceptor TypeScript Examples

The following examples show how to use @nestjs/platform-express#FileInterceptor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: gcloud-stroage-file.interceptor.ts    From nestjs-gcloud-storage with MIT License 6 votes vote down vote up
export function GCloudStorageFileInterceptor(
  fieldName: string,
  localOptions?: MulterOptions,
  gcloudStorageOptions?: Partial<GCloudStoragePerRequestOptions>,
): Type<NestInterceptor> {
  @Injectable()
  class MixinInterceptor implements NestInterceptor {
    public interceptor: NestInterceptor;

    constructor(private readonly gcloudStorage: GCloudStorageService) {
      this.interceptor = new (FileInterceptor(fieldName, localOptions))();
    }

    async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
      (await this.interceptor.intercept(context, next)) as Observable<any>;

      const request = context.switchToHttp().getRequest();
      const file = request[fieldName];

      if (!file) {
        Logger.error(
          'GCloudStorageFileInterceptor',
          `Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFileInterceptor('${fieldName}')?`,
        );
        return;
      }

      const storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions);
      file.storageUrl = storageUrl;
      return next.handle();
    }
  }

  const Interceptor = mixin(MixinInterceptor);
  return Interceptor as Type<NestInterceptor>;
}
Example #2
Source File: files.controller.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
@Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: (req: Express.Request, file: Express.Multer.File, cb) =>
          cb(null, 'public/uploads'),
        filename: (req: Express.Request, file: Express.Multer.File, cb) => {
          // mimetype: 'image/jpeg',
          const [, ext] = file.mimetype.split('/');
          FilesController.genericSercive.pcoket.filename = `${v4()}.${ext}`;
          cb(null, FilesController.genericSercive.pcoket.filename);
        },
      }),
      limits: {
        fileSize: 1e7, // the max file size in bytes, here it's 100MB,
        files: 1,
      },
    }),
  )
  uploadFile(@UploadedFile() file: Express.Multer.File): Promise<FileEntity> {
    const [, ext] = file.mimetype.split('/');
    this.saveImages(ext, file);
    return this.service.dbSave(
      file,
      FilesController.genericSercive.pcoket.filename,
    );
  }
Example #3
Source File: app.controller.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
@Post('/file')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads',
        filename: (req, file, callback) => {
          const uniqueSuffix =
            Date.now() + '-' + Math.round(Math.random() * 1e9);
          const ext = extname(file.originalname);
          const filename = `${uniqueSuffix}${ext}`;
          callback(null, filename);
        },
      }),
    }),
  )
  handleUpload(@UploadedFile() file: Express.Multer.File) {
    console.log('file', file);
    return 'File upload API';
  }
Example #4
Source File: file.decorator.ts    From aqualink-app with MIT License 6 votes vote down vote up
AcceptFile = (
  param: string,
  acceptTypes: string[],
  subfolder: string,
  prefix: string,
) => {
  const maxFileSizeMB = process.env.STORAGE_MAX_FILE_SIZE_MB
    ? parseInt(process.env.STORAGE_MAX_FILE_SIZE_MB, 10)
    : 1;
  const maxFileSizeB = maxFileSizeMB * 1024 * 1024;
  // Detach config object from MulterConfigurationOptions because
  // param acl is not currently documented in the types file of the extension 'multer-google-storage'
  // although the functionality for access control exists
  const config: any = {
    bucket: process.env.GCS_BUCKET,
    keyFilename: process.env.GCS_KEYFILE,
    projectId: process.env.GC_PROJECT,
    autoRetry: true,
    maxRetries: 3,
    filename: assignName(
      path.join(process.env.STORAGE_FOLDER || '', subfolder),
      prefix,
    ),
    acl: 'publicread',
  };
  if (!config.bucket) {
    console.warn('Configure a storage bucket to accept file uploads.');
    return UseInterceptors(MissingConfigInterceptor);
  }
  return UseInterceptors(
    FileInterceptor(param, {
      storage: new MulterGoogleCloudStorage(config),
      fileFilter: fileFilter(acceptTypes),
      limits: {
        fileSize: maxFileSizeB,
      },
    }),
  );
}
Example #5
Source File: profile.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('upload_profile_photo')
  @UseInterceptors(FileInterceptor('file'))
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    description: 'Upload avatar photo',
    type: AvatarUploadDto
  })
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiResponse({ type: UserDto, status: HttpStatus.OK })
  @HttpCode(HttpStatus.OK)
  async uploadFile(
    @UploadedFile() file: BufferedFile,
    @Req() req: Request
  ): Promise<UserDto> {
    if (!file) throw new BadRequestException('File image cannot be empty');

    if (file.mimetype.split('/')[0] !== 'image')
      throw new UnsupportedMediaTypeException('File is not an image');

    if (file.size / 1024 > 200)
      throw new BadRequestException('File cannot be larger than 200KB');

    const id = req.user['userId'];
    await this.profileService.uploadAvatar(file, id);
    const user = await this.userService.findByIdAsync(id);

    return plainToClass(UserDto, user, {
      enableImplicitConversion: true,
      excludeExtraneousValues: true
    });
  }
Example #6
Source File: tracks.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('create_with_thumbnail')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN, UserRole.MENTOR)
  @ApiResponse({ type: TrackDto, status: HttpStatus.CREATED })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, type: ApiException })
  @UseInterceptors(FileInterceptor('thumbnail'))
  @ApiConsumes('multipart/form-data')
  @ApiBearerAuth()
  async createTrack(
    @Body() input: CreateWithThumbnailTrackDto,
    @UploadedFile() thumbnail: BufferedFile,
    @Req() req: Request
  ): Promise<TrackDto> {
    if (!thumbnail)
      throw new BadRequestException('Thumbnail image cannot be empty');
    if (thumbnail.mimetype.split('/')[0] !== 'image')
      throw new UnsupportedMediaTypeException('File is not an image');
    if (thumbnail.size / ONE_KB > 200)
      throw new BadRequestException('File cannot be larger than 200KB');
    const exist = await this.trackService.findOneAsync({
      title: input.title.toUpperCase()
    });
    if (exist)
      throw new ConflictException(
        `Track with the title "${exist.title}" already exists`
      );

    const userId = req.user['userId'];
    const thumbnailUrl = await uploadFileToCloud(thumbnail, 'avatars', userId);
    const dto = input as any;
    dto.thumbnailUrl = thumbnailUrl;
    delete dto.thumbnail;
    return await super.create(dto);
  }
Example #7
Source File: MediaController.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
@Post()
  @HttpAuth(UserRole.ADMIN, UserRole.AUTHOR)
  @HttpCode(HttpStatus.OK)
  @UseInterceptors(FileInterceptor('file'))
  @ApiBearerAuth()
  @ApiConsumes('multipart/form-data')
  @ApiBody({type: HttpRestApiModelCreateMediaBody})
  @ApiQuery({name: 'name', type: 'string', required: false})
  @ApiQuery({name: 'type', enum: MediaType})
  @ApiResponse({status: HttpStatus.OK, type: HttpRestApiResponseMedia})
  public async createMedia(
    @Req() request: HttpRequestWithUser,
    @UploadedFile() file: MulterFile,
    @Query() query: HttpRestApiModelCreateMediaQuery
    
  ): Promise<CoreApiResponse<MediaUseCaseDto>> {
  
    const adapter: CreateMediaAdapter = await CreateMediaAdapter.new({
      executorId: request.user.id,
      name      : query.name || parse(file.originalname).name,
      type      : query.type,
      file      : file.buffer,
    });
    
    const createdMedia: MediaUseCaseDto = await this.createMediaUseCase.execute(adapter);
    this.setFileStorageBasePath([createdMedia]);
    
    return CoreApiResponse.success(createdMedia);
  }
Example #8
Source File: storage.controller.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
@Post()
	@HttpCode(204)
	@UseInterceptors(FileInterceptor('file'))
	@Permissions('storage/upload')
	public async upload(
		@Query('dir') dir = '',
		@UploadedFile() file: any
	): Promise<void> {
		const tenant = await this.tenantService.findOne();
		const StorageClient = this.storageLoader.load(tenant.settings.storageMedium || 'fs');
		const client = new StorageClient(tenant.settings.storageConfig);
		await client.init();

		return await client.put(`${dir}/${file.originalname}`.replace(/^(\/uploads)/, '').replace(/^\//, ''), file.buffer);
	}
Example #9
Source File: app.controller.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
@Post('build')
  @UseInterceptors(FileInterceptor('file'))
  async build(@UploadedFile() file) {
    const id = generateId();
    const path = unpackZip(file.buffer, id);
    this.appService.processBuild(path, id);
    return { id: id };
  }
Example #10
Source File: profile.controller.ts    From office-hours with GNU General Public License v3.0 5 votes vote down vote up
@Post('/upload_picture')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: memoryStorage(),
    }),
  )
  async uploadImage(
    @UploadedFile() file: Express.Multer.File,
    @User() user: UserModel,
  ): Promise<void> {
    if (user.photoURL) {
      fs.unlink(process.env.UPLOAD_LOCATION + '/' + user.photoURL, (err) => {
        console.error(
          'Error deleting previous picture at: ',
          user.photoURL,
          err,
          'the previous image was at an invalid location?',
        );
      });
    }

    const spaceLeft = await checkDiskSpace(path.parse(process.cwd()).root);

    if (spaceLeft.free < 1000000000) {
      // if less than a gigabyte left
      throw new ServiceUnavailableException(
        ERROR_MESSAGES.profileController.noDiskSpace,
      );
    }

    const fileName =
      user.id +
      '-' +
      Math.random().toString(36).substring(2, 15) +
      Math.random().toString(36).substring(2, 15);

    await sharp(file.buffer)
      .resize(256)
      .toFile(path.join(process.env.UPLOAD_LOCATION, fileName));

    user.photoURL = fileName;
    await user.save();
  }