Skip to content

Commit

Permalink
Merge pull request #2430 from micalevisk/patch-2
Browse files Browse the repository at this point in the history
docs(techniques): enhance `StreamableFile` code snippet
  • Loading branch information
kamilmysliwiec authored Aug 3, 2022
2 parents 90e2985 + a42c4e2 commit 2bcdb0a
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions content/techniques/streaming-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,33 @@ export class FileController {
}
```

The default content type is `application/octet-stream`, if you need to customize the response you can use the `res.set` method.
The default content type is `application/octet-stream`, if you need to customize the response you can use the `res.set` method or the [`@Header()`](/controllers#headers) decorator, like this:

```ts
import { Controller, Get, StreamableFile, Response } from '@nestjs/common';
import { Controller, Get, StreamableFile, Res } from '@nestjs/common';
import { createReadStream } from 'fs';
import { join } from 'path';
import type { Response } from 'express';

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

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

0 comments on commit 2bcdb0a

Please sign in to comment.