1.中間鍵使用 koa-bodynpm
npm install koa-body --save
const koaBody = require('koa-body'); app.use(koaBody({ multipart: true, formidable: { maxFileSize: 200 * 1024 * 1024 // 設置上傳文件大小最大限制,默認2M } }));
2.書寫路由,croller書寫方法
uploadData.jsjson
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.jsapp
//接收上傳的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 };