我正在探索如何使用 NestJs 和 TypeScript 上传 excel 文件,但无法在 StackOverflow 上获得正确的解决方案,所以我写了这个问题。
我想将以下名为“demo.xlsx”的文件上传到我的服务器:
它有以下数据:
我想将其上传到我给定的目录。
经过一些研发,我实现了这个解决方案,将 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)
}
这就是上传文件和其他数据的方法:
这就是我在 NestJS 中处理导入文件的方式。
npm 安装 multer
npm install --save @types/multer
@Post('import')
@UseInterceptors(
FileFieldsInterceptor([{
name: 'file',
maxCount: 1
}]),
)
async importUserData(
@UploadedFiles() files: {
file ? : Express.Multer.File[];
},
) {
console.log('file');
console.log(files);
}