首页 > Node.js实现本地客户端上传单个或者多个文件Excel文件(xls格式、xlsx格式文件)到服务器端,并且解析对应的Excel内容反馈�

Node.js实现本地客户端上传单个或者多个文件Excel文件(xls格式、xlsx格式文件)到服务器端,并且解析对应的Excel内容反馈�

 

 

注意,前情提示:

本代码基于《Node.js(nodejs)对本地JSON文件进行增、删、改、查操作(轻车熟路)》

传送门Node.js(nodejs)对本地JSON文件进行增、删、改、查操作(轻车熟路)_你挚爱的强哥❤给你发来1条消息❤-CSDN博客

 

在/api/demo/文件夹下面创建uploadExcel.js

代码内容

const $g = global.SG.$g, fs = global.SG.fs, router = global.SG.router, xlsx = global.SG.xlsx, multer = global.SG.multer, path = global.SG.path;
module.exports = global.SG.router;
const folderPath = "./temp/upload";//存储临时上传文件的路径
const maxFiles = 999999999;//最多支持同时上传文件数(留给客户端自由限制)
const mkdirs = $g.dir.mkdirsByFolderPath;//递归创建文件夹目录(基于文件夹路径)const upload = multer({storage: multer.diskStorage({destination(req, file, cb) {mkdirs(folderPath, () => cb(null, path.join(__dirname, `../../${folderPath}`)));//文件存储路径},filename(req, file, cb) {cb(null, `${file.fieldname}-${$g.date.timestamp()}-${file.originalname}`);//定义随机文件名}})
});//上传单个Excel(all方法支持POST、GET、PUT、PATCH、DELETE传参方式)
router.all("/demo/uploadExcel", upload.single("file"), (req, res) => {let filePath = req.file.path;fs.exists(filePath, exists => {if (exists) {let json = xlsx.parse(filePath);$g.json.res(req, res, "上传成功", json, true);$g.dir.delayDestroyFile(filePath);//延时60秒销毁服务器文件} else {$g.json.res(req, res, `文件路径${filePath}不存在}`, req.file, false);}});
});
//上传多个Excel(all方法支持POST、GET、PUT、PATCH、DELETE传参方式)
router.all("/demo/uploadExcel/multi", upload.array("file", maxFiles), (req, res) => {let arr = req.files, json = [];for (let i = 0, len = arr.length; i < len; i++) {let filePath = arr[i].path;json.push(xlsx.parse(filePath));$g.dir.delayDestroyFile(filePath);//延时60秒销毁服务器文件}$g.json.res(req, res, "上传成功", json, true);
});

在index.js最后一行加入

app.use(API_PATH, require(`.${API_PATH}/demo/uploadExcel`));//上传并解析Excel

运行

cnpm i node-xlsx & node index

更多相关:

  • 第一节 基于Struts 2完成文件上传 Struts 2框架中没有提供文件上传,而是通过Common-FileUpload框架或COS框架来实现的,Struts 2在原有上传框架的基础上进行了进一步封装,从而大大简化了文件上传的开发应用。 1.1 下载并安装Common-FileUpload框架   1.2 配置上传解析器 1.3...

  • 我使用七牛是因为我懒得管理图片,也懒得处理图片缩放之类的东西。 最主要的,感觉用七牛逼格比较高。 傻瓜式的顺序:注册七牛账号->实名认证->充值10块钱->开始使用 这时候你去个人中心->密钥管理,可以看到AK和SK两个值,这两个值是七牛确认是谁在上传图片,也就是确认身份用的,所以千万不要给心怀不轨的人看到。 图片上传应该都需要以下几...

  • 在经受一天的磨难之后终于找到处理事件方法: 先引用: