【问题标题】:How to get rid of "TypeError: req.pipe is not a function" nestjs and fastify如何摆脱“TypeError:req.pipe 不是函数”nestjs 和 fastify
【发布时间】:2020-05-22 03:59:46
【问题描述】:

我尝试使用 NestJS/Fastify 和 typescript 上传文件

这是main.ts

async function bootstrap() {
  //file upload with fastify
  const fastifyAdapter = new FastifyAdapter();
  fastifyAdapter.register(fmp, {
    limits: {
      fieldNameSize: 100, // Max field name size in bytes
      fieldSize: 1000000, // Max field value size in bytes
      fields: 10, // Max number of non-file fields
      fileSize: 100, // For multipart forms, the max file size
      files: 1, // Max number of file fields
      headerPairs: 2000, // Max number of header key=>value pairs
    },
  });

  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    fastifyAdapter,
  );
 await app.listen(3000);
  Logger.log('application started on http://localhost:3000', 'Bootstrap');
}
bootstrap();

这是file.controller.ts

@Post()
  @UseInterceptors(FileInterceptor('image'))
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    description: 'logo',
    type: UploadFileDto,
  })
  uploadedFile(@UploadedFile() file) {
    const response = {
      originalname: file.originalname,
      filename: file.filename,
    };
    return response;
  }

上传文件到这个action后,代码抛出这样的异常

TypeError: req.pipe 不是函数 在 multerMiddleware (D:\R.Khodabakhshi\Repository\raimun-web\node_modules\multer\lib\make-middleware.js:176:9) 在 Promise (D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\platform-express\multer\interceptors\file.interceptor.js:15:81) 在新的承诺 () 在 MixinInterceptor.intercept (D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\platform-express\multer\interceptors\file.interceptor.js:15:19) 在 D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\core\interceptors\interceptors-consumer.js:22:36 在 Object.handle (D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\core\interceptors\interceptors-consumer.js:20:56) 在 LoggingInterceptor.intercept (D:\R.Khodabakhshi\Repository\raimun-web\dist\shared\logging.interceptor.js:28:21) 在 D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\core\interceptors\interceptors-consumer.js:22:36 在 InterceptorsConsumer.intercept (D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\core\interceptors\interceptors-consumer.js:24:24) 在 D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\core\router\router-execution-context.js:45:60 [Nest] 10928 - 2020-02-06 10:10:49 [ExceptionFilter] undefined undefined +587529ms TypeError:req.pipe 不是函数 在 multerMiddleware (D:\R.Khodabakhshi\Repository\raimun-web\node_modules\multer\lib\make-middleware.js:176:9) 在 Promise (D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\platform-express\multer\interceptors\file.interceptor.js:15:81) 在新的承诺 () 在 MixinInterceptor.intercept (D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\platform-express\multer\interceptors\file.interceptor.js:15:19) 在 D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\core\interceptors\interceptors-consumer.js:22:36 在 Object.handle (D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\core\interceptors\interceptors-consumer.js:20:56) 在 LoggingInterceptor.intercept (D:\R.Khodabakhshi\Repository\raimun-web\dist\shared\logging.interceptor.js:28:21) 在 D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\core\interceptors\interceptors-consumer.js:22:36 在 InterceptorsConsumer.intercept (D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\core\interceptors\interceptors-consumer.js:24:24) 在 D:\R.Khodabakhshi\Repository\raimun-web\node_modules@nestjs\core\router\router-execution-context.js:45:60

我该如何解决这个问题???

【问题讨论】:

    标签: node.js typescript file-upload nestjs fastify


    【解决方案1】:

    问题已解决,正如Jay McDaniel 提到的,我们不能将FastifyAdapterFileInterceptor 一起使用。 我用这个小代码解决了这个问题。

    import {
      Controller,
      Logger,
      Post,
      Req,
      Res,
    } from '@nestjs/common';
    import * as fs from 'fs';
    import * as path from 'path';
    import * as pump from 'pump';
    const logger = new Logger('FileController');
    
    @ApiTags('File')
    @Controller('api/file')
    export class FileController {
      @Post()
      upload(@Req() req: any, @Res() reply: any): void {
          const mp = req.multipart(
          (field: any, file: any, filename: any, encoding: any, mimeType: any) => {
            console.log('save file from request ---- ', field, filename, mimeType);
            file.on('limit', () => logger.error('SIZE_LIMITED'));
    
            const filePath = path.resolve('./'+filename);
            const writeStream = fs.createWriteStream(filePath);
            pump(file, writeStream);
            writeStream.on('finish', () => {
              reply.code(200).send();
            });
          },
    
          (error: any) => {
            if (error) {
              logger.error(error);
              reply.code(500).send();
            }
          },
        );
        mp.on('partsLimit', () => logger.error('MAXIMUM_NUMBER_OF_FORM_PARTS'));
        mp.on('filesLimit', () => logger.error('MAXIMUM_NUMBER_OF_FILES'));
        mp.on('fieldsLimit', () => logger.error('MAXIMUM_NUMBER_OF_FIELD'));
      }
    }
    

    我希望这对你也有帮助......

    【讨论】:

      【解决方案2】:

      您不能将FastifyAdapterFileInterceptor 一起使用。 It says so in the beginning of the docs。如果你想使用 Fastify 和文件上传,你需要为它创建自己的拦截器。

      【讨论】:

      • 即使我使用了fastity-multipart包我也不能使用FileInterceptor
      • 也许我没有说清楚:FileInterceptor 在后台使用multer,这就是它的设计方式以及为什么在文档中它说“Multer 无法处理不在支持的多部分格式 (multipart/form-data)。另外,请注意此包与 FastifyAdapter 不兼容。"
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2020-05-22
      • 2020-05-09
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多