emis-oms-frontend/src/utils/oss/uploadOss.js
2024-06-12 06:20:13 +08:00

85 lines
2.2 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.

const OSS = require('ali-oss')
import {
stsToken
} from '@/api/oss.js'
let ossConfig = null;
// 取消上传控制项
let isCancel = false;
// 设置客户端请求访问凭证的地址
const OssFunc = async() => {
let res = await stsToken();
ossConfig = res.data;
const client = new OSS({
// yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
region: 'oss-cn-hangzhou',
accessKeyId: ossConfig.accessKeyId,
accessKeySecret: ossConfig.accessKeySecret,
stsToken: ossConfig.securityToken,
bucket: ossConfig.bucketName,
timeout: 600000,
// HTTPS (secure: true) or HTTP (secure: false) protocol
secure: false,
refreshSTSTokenInterval: 3000000,
refreshSTSToken: stsToken().then(res => {
if (res.status === 0) {
console.log('成功刷新oss token');
ossConfig.accessKeyId = res.data.accessKeyId;
ossConfig.accessKeySecret = res.data.accessKeySecret;
ossConfig.securityToken = res.data.securityToken;
}
})
});
return client;
};
// 分片上传方法(没有设置分片相关设置,采用默认)
async function put(fileName, file) {
try {
let oss = await OssFunc();
const result = await oss.multipartUpload(fileName, file, {
'headers': {
'Access-Control-Allow-Origin': '*',
},
'progress': (progress) => {
// console.log('progress:', progress)
if (isCancel) {
oss.cancel();
// 复位
isCancel = false;
}
}
});
return result;
} catch (e) {
console.log(e);
}
}
// 设置取消上传标志位为true
async function cancelUpload() {
isCancel = true;
return true;
}
// 获取oss文件临时路径
async function getUrl(name) {
try {
let oss = await OssFunc();
const result = await oss.signatureUrl(name);
return result;
} catch (e) {
console.log(e);
}
}
export {
put,
getUrl,
cancelUpload,
}