0

I am exploring how to upload the excel file using NestJs and TypeScript but couldn't get the correct solution on StackOverflow so I write this question.

I want to upload the below file with the name "demo.xlsx" to my server:

enter image description here

And it has the following data:

enter image description here

I want to upload it to my given directory.

Shubham Verma
  • 8,783
  • 6
  • 58
  • 79

1 Answers1

1

After some R&D I implemented this solution to upload the excel file in my given directory.

Create a directory "upload.ts" and add the below codes into it.

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

Now write the below code to upload the file, the below code in 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)
  }

And this the how you can upload the file along with other data:

enter image description here

Shubham Verma
  • 8,783
  • 6
  • 58
  • 79