NestJS でのストリーム ファイルの処理

REST API からクライアントにファイルを送り返したい場合があります。Nest でこれを行うには、通常、次のことを行う必要があります。

@Controller("file")
export class FileController {
    
    
  @Get()
  getFile(@Res() res: Response) {
    
    
    const file = createReadStream(join(process.cwd(), "package.json"));
    file.pipe(res);
  }
}

ただし、これを行うと、ポストコントローラーインターセプターロジックにアクセスできなくなります。これを処理するには、StreamableFile インスタンスを返すと、バックグラウンドでフレームワークが応答のパイプ処理を処理します。

クラスを使用してStreamableFileストリーミング ファイルを処理する

NestJS では、ストリーミング ファイルの処理に使用できますStreamableFile。新しい StreamableFile を作成するには、Buffer または Stream を StreamableFile コンストラクターに渡すことができます。次に、指定したディレクトリにあるファイルをブラウザに返すインターフェースを事前に作成します。具体的なコードは次のとおりです。

@Get('/model')
getFile(): StreamableFile {
    
    
  const file = createReadStream(join(process.cwd(), '../../public/model.xlsx'));
  return new StreamableFile(file);
}

StreamableFileデフォルトの応答ヘッダー タイプは ですapplication/octet-stream。フロントエンドは、このストリームを取得した後に特別な処理を行う必要があります。応答をカスタマイズする必要がある場合は、次に示すように、 res.set メソッドまたは @Header() デコレータを使用できます。

@Get()
getFile(@Res({
    
     passthrough: true }) res: Response): StreamableFile {
    
    
  const file = createReadStream(join(process.cwd(), '../../public/model.xlsx'));
  res.set({
    
    
    'Content-Type': 'application/json',
    'Content-Disposition': 'attachment; filename="model.xlsx"',
  });
  return new StreamableFile(file);
}

// Or even:
@Get()
@Header('Content-Type', 'application/json')
@Header('Content-Disposition', 'attachment; filename="model.xlsx"')
getStaticFile(): StreamableFile {
    
    
  const file = createReadStream(join(process.cwd(), '../../public/model.xlsx'));
  return new StreamableFile(file);
}

おすすめ

転載: blog.csdn.net/qq_33003143/article/details/132329669