0

I have to upload data of file into postgres database using nestjs.

below is the method which I am writing.

@Post('upload')
  @UseInterceptors(FileInterceptor('file', multerOptions))
  @UseInterceptors(FileInterceptor('file'))
  UploadExcelFile(@UploadedFile() file: Express.Multer.File) {
    console.log("Hello")
    console.log("Hello");
    console.log(file);
    const workBook: XLSX.WorkBook = XLSX.read(file.buffer, {
      type: 'buffer',
      cellDates: true,
      cellNF: false,
    });
    const sheetName = workBook?.SheetNames[0]; // asigne first sheet name of file
    const sheet: XLSX.WorkSheet = workBook.Sheets[sheetName]; // entire sheet information asigned to sheet variable
    
    const jsonData: FileUploadDto[] = XLSX.utils.sheet_to_json(sheet, {
      dateNF: 'YYYY-MM-DD',
    });
    // Add fields validation here
    console.log(jsonData);
    // return this.usersService.processFile(file);
  }

below is the multerconfig file.

import { extname } from 'path';
import { diskStorage } from 'multer';
import { v4 as uuid } from 'uuid';
import { HttpException, HttpStatus } from '@nestjs/common';

//Need to update proper location once portworx configured
export const multerConfig = {
    dest: process.env.UPLOAD_LOCATION,
};

export const multerOptions = {
    limits: {
        fileSize: +process.env.MAX_FILE_SIZE,
    },
    fileFilter: (_req: any, file: any, callback: any) => {
        if (file.mimetype.match('jpg|jpeg|png|gif|pdf|msg|eml|docx|doc|xlsx|xls')) {
            callback(null, true);
        } else {
            callback(
                new HttpException(
                    `Unsupported file type ${extname(file.originalname)}`,
                    HttpStatus.BAD_REQUEST
                ),
                false
            );
        }
    },
    storage: diskStorage({
        destination: multerConfig.dest,
        filename(_, file, callback) {
            /* istanbul ignore next */
            return callback(null, `${uuid()}${extname(file.originalname)}`);
        },
    }),
};

I am just trying to get data of file inside the method. later I will write the logic to insert into database . but when I am trying to access it is thrwing error.

enter image description here

below is my DTO file.

import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString, MaxLength } from 'class-validator';

    export class FileUploadDto {
     
      @IsString()
      @IsNotEmpty()
      @MaxLength(25)
      displayName: string;
    
      @IsString()
      @IsNotEmpty()
      @MaxLength(25)
      email: string;
    
      @IsString()
      @IsNotEmpty()
      @MaxLength(50)
      role: string;
    }

file contains valid data. but it is valid data. enter image description here

Shruti sharma
  • 199
  • 6
  • 21
  • 67

0 Answers0