mgh
mgh

Reputation: 407

Saving files in file system in Nestjs

I want to store the URL of images sent from client using multipart/form-datain my MySQL database. I followed the docs but I can't really find out how I should save an image in server file system and return the URL back to the client.

This is my code:

@ApiTags('product-image')
@Controller('product-image')
export class ProductImageController {
  constructor(public service: ProductImageService) {
  }

  @Post('upload')
  @UseInterceptors(FilesInterceptor('files'))
  uploadImage(@UploadedFiles() files) {
    console.log(files);
    // How can I save image files in
    // a custom path and return the path
    // back to the client?

  }
}

Upvotes: 9

Views: 26216

Answers (1)

Kallol Medhi
Kallol Medhi

Reputation: 589

try this

import { FilesInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';

@Post('upload')
    @UseInterceptors(
        FilesInterceptor('files', 20, {
          storage: diskStorage({
            destination: './uploads/',
            filename: editFileName,
          }),
        //   fileFilter: imageFileFilter,
        }),
      )
      uploadMultipleFiles(@UploadedFiles() files) {
        const response = [];
        files.forEach(file => {
          const fileReponse = {
            filename: file.filename,
          };
          response.push(fileReponse);
        });
        return response;
      }

Upvotes: 13

Related Questions