erp-el-element/utils/aliyun.oss.client.js

105 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 阿里云oss上传工具
*/
import { get_oss_sign_aliyun } from '@/api/user'
const OSS = require('ali-oss')
const config = {
region: 'oss-cn-shenzhen',
accessKeyId: 'LTAIyZIrTMnMYzZ8',
accessKeySecret: 'bte644kZ70psfTenXE0IbSSQk040u1',
// accessKeySecret: '1',
policy: '',
bucket: 'aiguovip2020'
}
/**
* 配置
*/
const init = async(v) => {
const res = await get_oss_sign_aliyun({ type: v })
config.region = res.datas.region
config.accessKeyId = res.datas.accessid
config.signature = res.datas.signature
config.policy = res.datas.policy
config.bucket = res.datas.bucket
console.log(config)
return new OSS(config)
}
/**
* 生成uuid
*/
const guid = () => {
const S4 = () => {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
}
/**
* 修改文件名字
*/
const fileName = (file) => {
const arr = file.name.split('.')
var uuid = 'oss' + guid()
if (arr.length > 1) {
return uuid + '.' + arr[arr.length - 1]
} else {
return uuid
}
}
/**
* 上传文件
*/
const ossPut = (file, dir) => {
return new Promise((resolve, reject) => {
const objectName = fileName(file)
init().put(dir + objectName, file).then(({ res, url }) => {
if (res && res.status == 200) {
resolve(res, url)
}
}).catch((err) => {
reject(err)
})
})
}
// 直接调取oss函数返回URL结果
function uploadOSS(file) {
return new Promise(async(resolve, reject) => {
const fileName = fileName(file)
// let client = new OSS({
// region: OSSConfig.ossParams.region,
// accessKeyId: OSSConfig.ossParams.accessKeyId,
// accessKeySecret: OSSConfig.ossParams.accessKeySecret,
// bucket: OSSConfig.ossParams.bucket,
// secure: true
// })
const res = await init().multipartUpload(dir + fileName, file)
if (res.name) {
resolve({
fileName: file.name,
url: `${OSSConfig.uploadHost}/${fileName}`
})
} else {
reject('OSS上传失败')
}
})
}
/**
* 下载文件
*/
const ossGet = (name) => {
return new Promise((resolve, reject) => {
init().get(name).then(({ res }) => {
if (res && res.status == 200) {
resolve(res)
}
}).catch((err) => {
reject(err)
})
})
}
export default { ossPut, ossGet, uploadOSS, init }