使用 NestJs 和 TypeScript 上传 Excel 文件

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

我正在探索如何使用 NestJs 和 TypeScript 上传 excel 文件,但无法在 StackOverflow 上获得正确的解决方案,所以我写了这个问题。

我想将以下名为“demo.xlsx”的文件上传到我的服务器:

它有以下数据:

我想将其上传到我给定的目录。

excel typescript upload nest
2个回答
1
投票

经过一些研发,我实现了这个解决方案,将 excel 文件上传到我给定的目录中。

创建一个目录“upload.ts”并将以下代码添加到其中。

import { extname } from 'path';
import { existsSync, mkdirSync } from 'fs';
import { diskStorage } from 'multer';
import { HttpException, HttpStatus } from '@nestjs/common';

export const PATH_DOWNLOADED_FILE = `src/common/utils`;
export const SUPPORTED_FILES = ['jpg', 'xlsx', 'sheet', 'jpeg', 'png', 'gif'];


export const multerConfig = {
    dest: process.env.UPLOAD_LOCATION || './',
};

export const multerOptions = {
    limits: {
        fileSize: +process.env.MAX_FILE_SIZE || 1024 * 20,
    },
    fileFilter: (req: any, file: any, cb: any) => {
        const ext: string = file.originalname.split('.').pop() || '';
        if (SUPPORTED_FILES.indexOf(ext?.toLowerCase()) !== -1) {
            cb(null, true);
        } else {
            cb(new HttpException(`Unsupported file type ${extname(file.originalname)}`, HttpStatus.BAD_REQUEST), false);
        }
    },
    storage: diskStorage({
        /* Destination storage path details */
        destination: (req: any, file: any, cb: any) => {
            const uploadPath = multerConfig.dest;
            /* Create folder if doesn't exist */
            if (!existsSync(PATH_DOWNLOADED_FILE)) {
                mkdirSync(PATH_DOWNLOADED_FILE);
            }
            cb(null, PATH_DOWNLOADED_FILE);
        },
        /* File modification details */
        filename: (req: any, file: any, cb: any) => {
            /* Calling the callback passing the random name generated with the original extension name */
            cb(null, `AA${file.originalname}`);
        },
    }),
};

现在编写以下代码来上传文件,以下代码在Nest.js中:

import {
    Body,
    HttpException,
    Post,
    UseInterceptors, UploadedFile
  } from "@nestjs/common";
import { FileInterceptor } from '@nestjs/platform-express'
import { multerOptions, SUPPORTED_FILES } from 'src/common/utils/upload';


export class ReqBodyDto {
    @ApiProperty({ required: true })
    @IsNotEmpty()
    MACode: string;
  
    @ApiProperty({ required: true })
    @IsNotEmpty()
    chunkSize: string;
  }


  @Post("/v1/upload")
  @UseInterceptors(FileInterceptor('file', multerOptions))
  async upload(@UploadedFile() file, @Body() body: ReqBodyDto) {
    console.log(`body : ${JSON.stringify(body)}`);
    if (!file) {
      throw new HttpException(
        `Please provide correct file name with extension ${JSON.stringify(SUPPORTED_FILES)}`,
        400
      );
    }
    console.log(`Migration file: ${JSON.stringify(file)}`);
    return this.uploadFileWithInfo(file, body);
  }




  async uploadFileWithInfo(file: any, body: ReqBodyDto) {
    console.log(`uploadFileWithInfo:${JSON.stringify(file)}`)
    const { originalname, filename: sourceFileName } = file;
    const { chunkSize = 100 } = body;
    console.log(originalname, sourceFileName, chunkSize)
  }

这就是上传文件和其他数据的方法:


0
投票

这就是我在 NestJS 中处理导入文件的方式。

  1. 我首先导入必要的模块

npm 安装 multer

npm install --save @types/multer

  • 还要确保您安装了 @nestjs/platform-express 模块。该模块将 Express 框架合并到 NestJS 中。
  • Multer,一个专为处理多部分/表单数据而设计的 Node.js 中间件,用于有效的文件上传处理。
  1. 添加控制器。

@Post('import')
@UseInterceptors(
  FileFieldsInterceptor([{
    name: 'file',
    maxCount: 1
  }]),
)
async importUserData(
  @UploadedFiles() files: {
    file ? : Express.Multer.File[];
  },
) {
  console.log('file');
  console.log(files);
}

  • FileFieldsInterceptor 表示端点期望上传字段名为“file”的文件,最多允许一个文件。我还可以添加任意数量的文件。
  • 当您需要获取通过请求上传的文件时,
  • @UploadedFiles()装饰器会派上用场。在函数参数中,“files”对象预计包含一个“file”字段,其中包含上传文件的数组。在 Node.js 生态系统中,尤其是在使用 Multer 中间件时,通常的做法是使用 Express.Multer.File[] 类型来表征这些上传的文件
您现在可以访问控制器中的一组文件。

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