提问者:小点点

导入csv文件并发送到后端


我尝试创建一个redux-react应用程序,在该应用程序中,用户可以导入一个CSV文件,然后将其存储在数据库中。现在,我在前端工作,我想在那里创建一个代码,用户可以选择一个csv文件,从他们的计算机,他们想下载,然后文件发送到后端。我已经使用csvReader读取CSV文件,但我不知道如何将数据发送到后端。我在后端使用nestJS。我想一次发送整个CSV文件,但我不知道如何解决这个问题。我是初学者你知道怎么解决我的问题吗?


共1个答案

匿名用户

我不能帮助你的反应,但也许这个NestJS部分可以帮助你。您可以使用multer配置api并设置存储路径。

>

  • 创建multer选项

    // multer.ts
    
    const excelMimeTypes = [
       'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
       'application/wps-office.xlsx',
       'application/vnd.ms-excel',
    ];
    
    export const multerOptions = {
       fileFilter: (req: any, file: any, cb: any) => {
          const mimeType = excelMimeTypes.find(im => im === file.mimetype);
    
           if (mimeType) {
              cb(null, true);
           } else {
              cb(new HttpException(`Unsupported file type ${extname(file.originalname)}`, HttpStatus.BAD_REQUEST), false);
        }
    },
    storage: diskStorage({
        destination: (req: any, file: any, cb: any) => {
            const uploadPath = '/upload'; // use env var
            if (!existsSync(uploadPath)) {
                mkdirSync(uploadPath);   // create if not exists
            }
            cb(null, uploadPath);
        },
        filename: (req: any, file: any, cb: any) => {
            cb(null, file.originalname);
        },
     }),
    };
    

    导入最近创建的multerOption并使用FileInterceptor和UploadedFile装饰器获取文件。

    @Post()
    @UseInterceptors(FileInterceptor('file', multerOptions))
    uploadFile(@UploadedFile() file) {
        console.log(file) // call service or whathever to manage uploaded file.. handleFile in the example below..
    }
    

    使用xlsx库管理文件(示例)。

    handleFile(file: any): Promise<any> {
        return new Promise(async (resolve: (result: any) => void, reject: (reason: any) => void): Promise<void> => {
            try {
                const workbook = XLSX.readFile(`${uploadLocation}/${file.filename}`);
                resolve(workbook.Sheets[sheetName]);
            } catch (error) {
                reject(error);
            }
        });
    }
    

    希望有帮助!