4

1.中间键使用 koa-body

npm install koa-body --save
const koaBody = require('koa-body');

app.use(koaBody({
  multipart: true,
  formidable: {
    maxFileSize: 200 * 1024 * 1024 // 设置上传文件大小最大限制,默认2M
  }
}));

2.书写路由,croller书写方法
uploadData.js

const errorResult = require('../utils/errorResult.js');
const uploadExcelSrv = require('../service/uploadExcelSrv');

const saveData = async function (ctx, next) {

  const getRes = await uploadExcelSrv.getExcelObjs(ctx);
  if (getRes.status) {
    if (getRes.datas.length > 1) {
      errorResult.errorRes(ctx, '暂时不支持多个sheet存在');
    } else { //得到的是数组
      const objs = getRes.datas[0];
      ctx.body = {
        status: true,
        msg: '上传数据成功'
      };
    }
  } else {
    errorResult.errorRes(ctx, getRes.msg);
  }
  await next();
};
module.exports = {
  saveData
};

3.处理excel存储,解析,处理excel用的库是 xlsx

npm install xlsx --save

uploadExcelSrv.js

//接收上传的excel文件,保存解析返回objects
const xlsx = require('xlsx');
const fs = require('fs');
const path = require('path');
const downPath = path.resolve(__dirname, '../../fileUpload');

async function getExcelObjs (ctx) {
  const file = ctx.request.files.file; // 获取上传文件
  const reader = fs.createReadStream(file.path); // 创建可读流
  const ext = file.name.split('.').pop(); // 获取上传文件扩展名
  const filePath = `${downPath}/${Math.random().toString()}.${ext}`;

  const upStream = fs.createWriteStream(filePath); // 创建可写流
  const getRes = await getFile(reader, upStream); //等待数据存储完成

  const datas = []; //可能存在多个sheet的情况
  if (!getRes) { //没有问题
    const workbook = xlsx.readFile(filePath);
    const sheetNames = workbook.SheetNames; // 返回 ['sheet1', ...]
    for (const sheetName of sheetNames) {
      const worksheet = workbook.Sheets[sheetName];
      const data = xlsx.utils.sheet_to_json(worksheet);
      datas.push(data);
    }
    return {
      status: true,
      datas
    };
  } else {
    return {
      status: false,
      msg: '上传文件错误'
    };
  }
}

function getFile (reader, upStream) {
  return new Promise(function (result) {
    let stream = reader.pipe(upStream); // 可读流通过管道写入可写流
    stream.on('finish', function (err) {
      result(err);
    });
  });
}
module.exports = {
  getExcelObjs
};

小谷xg
2.3k 声望297 粉丝

明月清风自在怀,任重道远常心态。坎坷人生从容走,否极自有安泰来。