【问题标题】:Import csv file and send to backend导入 csv 文件并发送到后端
【发布时间】:2020-08-08 01:31:02
【问题描述】:

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

【问题讨论】:

    标签: csv redux frontend backend nestjs


    【解决方案1】:

    我无法帮助您做出反应,但也许这个 NestJS 部分可以帮助您。您可以使用multer 来配置您的 api 并设置存储路径。

    1. 创建多重选项

      // 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);
          },
       }),
      };
      
    2. 导入最近创建的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..
      }
      
    3. 使用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);
              }
          });
      }
      

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2021-06-06
      相关资源
      最近更新 更多