Nzoni docs
  • Getting Started
  • Angular
    • Project Structure
    • Authentication, Magic Link and Google Auth
    • Landing page
    • Payments and Plans
    • Blog and articles
    • User Dashboard
    • Admin Dashboard
    • SEO & SSR
    • Deploy Angular Project
  • Nest.js
    • Project Structure
    • Authentication, Google auth and Magic link
    • Blogposts
    • Plans
    • Stripe Payment
    • Email and Templates
    • Database and Migration
    • Image File upload
    • Users
    • Deploy Nest.js project
  • Node.js/MongoDB
    • Project structure
    • API endpoints
  • Angular / Firebase / Node.js
  • Create first and default plan
  • Create an Admin User
  • Support
  • Licenses
Powered by GitBook
On this page
  • File upload module path
  • Upload an image
  • Read an image
  1. Nest.js

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`);
    }
  }
PreviousDatabase and MigrationNextUsers

Last updated 1 year ago