utils/index.js
/**
* 獲取文件后綴
* */
export function getSuffix (filePath) {
return `.${filePath.split('.').pop()}`
}
/**
* 隨機(jī)數(shù)
* */
export function random (len) {
let s = ''
while (s.length < len) {
const r = Math.random()
s += (r < 0.1 ? Math.floor(r * 100) : String.fromCharCode(Math.floor(r * 26) + (r > 0.5 ? 97 : 65)))
}
return s
}
import { toast, random, getSuffix } from '@/utils/index'
import OSS from 'ali-oss'
let fileList = []
// 獲取oss信息
fileToken({ privateBucketName: false }).then(({ code, data, msg }) => {
if (code) return
ossData = data
// OSS初始化
client = new OSS({
region: 'oss-cn-hangzhou',
accessKeyId: data.accessKeyId,
accessKeySecret: data.accessKeySecret,
bucket: data.bucketName,
stsToken: data.securityToken,
refreshSTSToken: 1617022351
})
})
// 上傳
function uploadFile(file) {
const objectKey = ossData.directory + random(18) + getSuffix(file.file.name)
try {
client.put(objectKey, file.file)
.then(result => {
fileList.push({ url: result.url })
emit('update:value', fileList.value)
})
} catch (e) {
toast(`${file.file.name}${t('i18n_upload_pic_tips_02')}`)
}
}