Skip to content

Commit 09a0ecf

Browse files
committed
Check uploaded image size
1 parent 4d8df92 commit 09a0ecf

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

apps/api/src/images/images.service.ts

+13-8
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Injectable } from '@nestjs/common';
1+
import { BadRequestException, Injectable, PayloadTooLargeException } from '@nestjs/common';
22
import { Document } from 'mongoose';
33
import { ImageDto } from 'shared-types/dist/ImageDto';
44
import { S3CacheService } from '../s3-cache/s3-cache.service';
@@ -33,18 +33,23 @@ export class ImagesService {
3333
await this.s3Service.deleteObject(document.imageKey);
3434
}
3535
if (shouldUploadImage) {
36-
return this.uploadBase64(dto.data);
36+
const buffer = this.base64ToBuffer(dto.data);
37+
38+
const oneMb = 1000000;
39+
const fileToLarge = buffer.byteLength > 5 * oneMb;
40+
41+
if (fileToLarge) {
42+
throw new PayloadTooLargeException('Max image size is 5MB');
43+
}
44+
45+
const key = await this.s3Service.uploadObject(buffer);
46+
return key;
3747
}
48+
3849
return null;
3950
}
4051

4152
private base64ToBuffer(base64: string) {
4253
return Buffer.from(base64.replace(/^data:image\/\w+;base64,/, ''), 'base64');
4354
}
44-
45-
private async uploadBase64(base64: string) {
46-
const buffer = this.base64ToBuffer(base64);
47-
const key = await this.s3Service.uploadObject(buffer);
48-
return key;
49-
}
5055
}

0 commit comments

Comments
 (0)