Image File upload

File upload module path

├── node_modules
├── mail-templates
├── migrations
├── src
│   ├── configs
│   ├── domains
│   │   ├── file-uploads      # File uploads module

Upload an image

Find out the root below in the controller src/domains/file-uploads/file-uploads.controller.ts

  @Post('/image')
  @ApiOperation({
    operationId: 'Upload an image',
    description: 'Upload a file containing an image',
  })
  @UseInterceptors(
    FileInterceptor('file', {
      fileFilter: (req, file, cb) => {
        if (file.size > 1000 * 1000) {
          cb(new BadRequestException('Image is too large'), false);
        } else if (!file.mimetype.startsWith('image')) {
          cb(new BadRequestException('Invalid file format'), false);
        } else {
          cb(null, true);
        }
      },
    }),
  )
  async uploadImage(@UploadedFile() file): Promise<FileUpload> {
    return await this.service.saveFile(file, 'image');
  }

Read an image

Find out the root below in the controller src/domains/file-uploads/file-uploads.controller.ts

  @Get('/:id/image')
  @ApiOperation({
    operationId: 'Get an image',
  })
  async getImage(@Res() res, @Param('id') id: number) {
    const image = await this.service.repo.findOne({ where: { id, type: 'image' }});
    if (!!image && existsSync(image.path)) {
      res.set('Content-Type', image.mimetype);
      createReadStream(image.path).pipe(res);
    } else {
      throw new BadRequestException(`File with id ${id} does not exists`);
    }
  }

Last updated