0

我在里面创建一个拦截器,我想使用 FileInterceptor 但在 FileInterceptor 之后我收到错误声明

import { CallHandler, ExecutionContext, Injectable, NestInterceptor, UseInterceptors } from '@nestjs/common';
import { Observable } from 'rxjs';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';

@Injectable()
export class UploaderInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

    @UseInterceptors(FileInterceptor('file', {
      storage: diskStorage({
          destination: './uploads'
          , filename: (req, file, cb) => {
              // Generating a 32 random chars long string
              const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')
              //Calling the callback passing the random name generated with the original extension name
              cb(null, `${randomName}${extname(file.originalname)}`)
          }
      })
  }));


    return next.handle();
  }
}
4

1 回答 1

2

FileInterceptor是一个mixin含义,它是一个返回类的函数。此函数接受拦截器实际使用的配置。您可以做的不是尝试创建一个在后台使用拦截器或扩展它的类,而是为配置创建一个别名,如下所示:

export const UploadInterceptor = FileInterceptor('file', {
  storage: diskStorage({
      destination: './uploads',
      filename: (req, file, cb) => {
        // Generating a 32 random characters long string
        const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')
        //Calling the callback passing the random name generated with the original extension name
        cb(null, `${randomName}${extname(file.originalname)}`)
      }
  })
})

现在有了这个导出的常量(实际上是一个类),您就可以像这样使用拦截器了:

@Controller('upload')
export class UploadController {

  @UseInterceptors(UploadInterceptor)
  @Post()
  uploadFile() {
  // do logic;
  }
}

一切都应该适合你。

于 2020-04-08T06:53:39.740 回答