Skip to content

Instantly share code, notes, and snippets.

@AjayPoshak
Created May 15, 2023 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AjayPoshak/bf6aee32ef1fb155978176b02b1dfb5c to your computer and use it in GitHub Desktop.
Save AjayPoshak/bf6aee32ef1fb155978176b02b1dfb5c to your computer and use it in GitHub Desktop.
Streaming file from S3 NestJS
@Get(':hash')
@Header('Content-Type', 'image/png')
async getActiveImageByHash(
@Param('hash') hash: string,
@Res() response: Response,
): Promise<any> {
const res = await this.usersService.getActiveImageByHash(hash);
// Connect to s3
const client = new S3Client({
region: REGION,
credentials: {
accessKeyId: AWS_ACCESS_KEY,
secretAccessKey: AWS_SECRET_KEY,
},
});
const command = new GetObjectCommand({
Bucket: BUCKET,
Key: res[0].active_image,
});
// Get Object from S3
const obj = await client.send(command);
// Read object body which is often a stream of bytes
const { Body } = obj;
// @ts-ignore
Body.pipe(response); // Connecting the read stream to write stream so that S3 read can be streamed to API response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment