fix: fileName 去掉随机数

This commit is contained in:
wangfupeng 2020-11-20 10:30:29 +08:00
parent 565ddb3f34
commit d7a3a34a38
2 changed files with 35 additions and 5 deletions

View File

@ -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({

View File

@ -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)
})