From d7a3a34a3832135b07f2c383de6011b5829a875b Mon Sep 17 00:00:00 2001 From: wangfupeng Date: Fri, 20 Nov 2020 10:30:29 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20fileName=20=E5=8E=BB=E6=8E=89=E9=9A=8F?= =?UTF-8?q?=E6=9C=BA=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/controller/save-file.js | 36 ++++++++++++++++++++++++++++++++-- src/menus/img/upload-img.ts | 4 +--- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/server/controller/save-file.js b/server/controller/save-file.js index dc3896e..bd30b49 100644 --- a/server/controller/save-file.js +++ b/server/controller/save-file.js @@ -12,6 +12,32 @@ const FILE_FOLDER = 'upload-files' const isWindows = os.type().toLowerCase().indexOf('windows') >= 0 const TMP_FOLDER = 'upload-files-tmp' +/** + * 获取随机数 + */ +function getRandom() { + return Math.random().toString(36).slice(-3) +} + +/** + * 给文件名加后缀,如 a.png 转换为 a-123123.png + * @param {string} fileName 文件名 + */ +function genRandomFileName(fileName = '') { + // 如 fileName === 'a.123.png' + + const r = getRandom() + if (!fileName) return r + + const length = fileName.length // 9 + const pointLastIndexOf = fileName.lastIndexOf('.') // 5 + if (pointLastIndexOf < 0) return `${fileName}-${r}` + + const fileNameWithOutExt = fileName.slice(0, pointLastIndexOf) // "a.123" + const ext = fileName.slice(pointLastIndexOf + 1, length) // "png" + return `${fileNameWithOutExt}-${r}.${ext}` +} + /** * 保存上传的文件 * @param {Object} req request @@ -42,16 +68,22 @@ function saveFiles(req) { // 遍历所有上传来的图片 objForEach(files, (name, file) => { + console.log('name...', name) + // 图片临时位置 const tempFilePath = file.path // 图片名称和路径 - const fileName = name + const fileName = genRandomFileName(name) // 为文件名增加一个随机数,防止同名文件覆盖 + console.log('fileName...', fileName) const fullFileName = path.join(storePath, fileName) + console.log('fullFileName...', fullFileName) // 将临时文件保存为正式文件 fs.renameSync(tempFilePath, fullFileName) // 存储链接 - imgLinks.push(`/server/${FILE_FOLDER}/` + fileName) + const url = `/server/${FILE_FOLDER}/` + fileName + imgLinks.push(url) }) + console.log('imgLinks...', imgLinks) // 返回结果 resolve({ diff --git a/src/menus/img/upload-img.ts b/src/menus/img/upload-img.ts index 064c71b..44df849 100644 --- a/src/menus/img/upload-img.ts +++ b/src/menus/img/upload-img.ts @@ -4,7 +4,7 @@ */ import Editor from '../../editor/index' -import { arrForEach, forEach, getRandom } from '../../utils/util' +import { arrForEach, forEach } from '../../utils/util' import post from '../../editor/upload/upload-core' import Progress from '../../editor/upload/progress' @@ -180,8 +180,6 @@ class UploadImg { if (resultFiles.length > 1) { // 多个文件时,filename 不能重复 name = name + (index + 1) - } else { - name = name + getRandom() } formData.append(name, file) })