1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Node.js实现本地客户端上传单个或者多个文件Excel文件(xls格式 xlsx格式文件)到服

Node.js实现本地客户端上传单个或者多个文件Excel文件(xls格式 xlsx格式文件)到服

时间:2024-03-18 05:35:37

相关推荐

Node.js实现本地客户端上传单个或者多个文件Excel文件(xls格式 xlsx格式文件)到服

注意,前情提示:

本代码基于《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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。