上传图片功能,如果都将文件塞到一个文件夹内,后期文件多后不好维护。
上传到时候指定年月目录,上传到指定的月目录
const path = require('path') const fs = require('fs') // multer const multer = require('@koa/multer'); //上传文件存放路径、及文件命名 const storage = multer.diskStorage({ destination: function (req, file, cb) { let year = new Date().getFullYear() let month = new Date().getMonth() + 1 month = month.length == 2 ? month : '0' + month //判断目录是否存在,没有则创建 if (!fs.existsSync(`./img/${year}/${month}`)) { fs.mkdirSync(`./img/${year}/${month}`, { recursive: true }); } // 像req挂载一些参数,用于写入sql req['folderPath'] = `/img/${year}/${month}` req['year'] = year req['month'] = month cb(null, `./img/${year}/${month}`) }, filename: function (req, file, cb) { // 处理文件名有 . 的后缀名 let splitArr = file.originalname.split('.') let type = splitArr[splitArr.length - 1] let fileName = `${file.fieldname}_${Date.now().toString(16)}.${type}` // 像req挂载一些参数,用于写入sql req['fileName'] = fileName cb(null, fileName) } }) //文件上传限制 const limits = { fields: 10,//非文件字段的数量 fileSize: 5000 * 1024,//文件大小 单位 b files: 1//文件数量 } const upload = multer({ storage, limits }) module.exports = upload
还没有评论,来说两句吧...