使用nestjs将excel数据上传到数据库

问题描述 投票:0回答:1

我必须使用nestjs将文件数据上传到postgres数据库。

以下是我正在写的方法。

@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);
  }

下面是 multerconfig 文件。

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)}`);
        },
    }),
};

我只是想获取方法内的文件数据。稍后我将编写插入数据库的逻辑。但是当我尝试访问它时抛出错误。

enter image description here

下面是我的 DTO 文件。

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;
    }

文件包含有效数据。但这是有效数据。 enter image description here

javascript node.js express nestjs nestjs-config
1个回答
0
投票

删除@UseInterceptores(FileInterceptor('file') 线 并在邮递员中传递文件时在 key obv 中写入“文件”而不用“”

© www.soinside.com 2019 - 2024. All rights reserved.