Commit 173af669 by chenwq

动态获取OSS临时访问凭证;添加唯一上传目录。

1 parent f9ac2c03
import httpClient from '../plugin/axios/httpClient'
class OssConfigService {
/**
* 从接口获取OSS基础配置
* @returns {Promise<Object>} OSS配置对象
* @throws {Error} 当获取配置失败时抛出错误
*/
static async fetchApiConfig(bucketName, systemSource = 'dj') {
// 使用封装后的httpClient
const config = await httpClient.post('dj.api.script.common.aliyun.oss.acs.sts.credentials/1.0.0?bucketName=' + bucketName + '&systemSource=' + systemSource, { bucketName: bucketName, systemSource: systemSource })
// 验证配置结构
if (!config) {
throw new Error('无效的OSS配置格式')
}
return config.data
}
/**
* 从配置服务获取OSS基础配置
* @returns {Promise<Object>} OSS配置对象
* @throws {Error} 当获取配置失败时抛出错误
*/
static async fetchBaseConfig() {
// 使用封装后的httpClient
const config = await httpClient.get('https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=glsk-oss-config')
return config.data
}
}
export default OssConfigService
This diff could not be displayed because it is too large.
......@@ -11,6 +11,9 @@
"author": "liwk",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.28.0",
"@babel/preset-env": "^7.28.0",
"@rollup/plugin-json": "^6.1.0",
"rollup": "^1.32.1",
"rollup-plugin-babel": "^4.4.0",
"rollup-plugin-commonjs": "^10.1.0",
......@@ -21,6 +24,7 @@
"rollup-plugin-uglify": "^6.0.4"
},
"dependencies": {
"ali-oss": "^6.23.0"
"ali-oss": "^6.23.0",
"axios": "^1.11.0"
}
}
import axios from 'axios'
const baseURL = 'https://dj.test.glsx.com.cn/rop-dj-script/router/' // 必须配置
const httpClient = axios.create({
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
})
// 请求拦截器
httpClient.interceptors.request.use(config => {
config.baseURL = config.baseURL || baseURL
return config
})
// 响应拦截器
httpClient.interceptors.response.use(
response => {
return response.data
}, // 直接返回data字段
error => {
console.error('请求失败:', error)
return Promise.reject(error)
}
)
export default httpClient
import json from '@rollup/plugin-json' // 引入 JSON 插件
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
// import { eslint } from 'rollup-plugin-eslint'
......@@ -15,6 +16,7 @@ export default {
name: packages.name
},
plugins: [
json(),
resolve(),
commonjs(),
// eslint({
......
const OSS = require("ali-oss")
import OSS from 'ali-oss'
import OssConfigService from '../common/ossConfigService' // 导入配置服务
class GlOssApi {
constructor(params = {}) {
this.baseConfig = params.baseConfig
this.baseConfig = null
}
/**
* 分片上传大文件到阿里云OSS(带断点续传和重试机制)
* @param {*} file 文件流(大文件)
* @param {*} successCallback 成功回调
* @param {*} errCallBack 失败回调
* @param {*} bucketName 桶名(可选)
* @param {*} dir 上传目录(可选)
* @param {*} partSize 分片大小(单位 KB,默认500KB)
* @param {*} maxRetries 最大重试次数(默认3次)
*/
multipartUpload (
file,
successCallback = new Function(),
errCallBack = new Function(),
bucketName = "zzl-filerepostorypublic",
dir = "image",
partSize = 500, // 默认分片大小为500KB
maxRetries = 3 // 最大重试次数
) {
const { baseConfig } = this
if (!baseConfig) errCallBack(new Error("初始化缺少baseConfig配置"))
const fileName = file.name
const client = new OSS({
accessKeyId: baseConfig.alyOss2.accessKeyId,
accessKeySecret: baseConfig.alyOss2.accessKeySecret,
bucket: baseConfig.alyOss2.bucket,
endpoint: baseConfig.alyOss2.endpoint
})
if (partSize < 100) {
console.error("分片大小不能小于100KB")
errCallBack(new Error("分片大小不能小于100KB"))
return
}
// 确保目录以斜杠结尾
if (!dir.endsWith("/")) {
dir += "/"
}
const key = dir + fileName
let retryCount = 0
let currentCheckpoint = null
const uploadWithRetry = () => {
client
.multipartUpload(key, file, {
partSize: partSize * 1024, // 转换为字节
checkpoint: currentCheckpoint, // 使用上次的断点信息
progress: function (p, checkpoint) {
currentCheckpoint = checkpoint
console.log(`上传进度: ${p * 100}%`)
}
})
.then((result) => {
const size =
file.size > 1000000
? parseFloat(file.size / 1000000).toFixed(2) + "M"
: parseFloat(file.size / 1000).toFixed(2) + "KB"
console.log(result.res)
let [aliyunAddress] = result.res.requestUrls
console.log(aliyunAddress, "aliyunAddress")
let url = aliyunAddress.split("?")[0].split("https:")[1]
console.log(url, "url")
* 确保获取基础配置(如果尚未获取)
* @returns {Promise<void>}
*/
async ensureApiConfig(bucketName, systemSource = 'dj') {
this.apiBaseConfig = await OssConfigService.fetchApiConfig(bucketName, systemSource)
}
/**
* 分片上传大文件到阿里云OSS(带断点续传和重试机制)
* @param {File} file 文件对象
* @param {Function} successCallback 成功回调
* @param {Function} errCallBack 失败回调
* @param {string} bucketName 桶名(可选)
* @param {string} dir 上传目录(可选)
* @param {Object} custAttrObj 自定义属性对象(可选)
* @param {Object} compressObj 压缩配置对象(可选)
* @param {number} partSize 分片大小(单位 KB,默认500KB)
* @param {number} maxRetries 最大重试次数(默认3次)
*/
async multipartUpload(file, successCallback = () => {}, errCallBack = () => {}, bucketName = 'zzl-filerepostorypublic', dir = 'image', custAttrObj = { systemSource: 'dj' }, compressObj = {}, partSize = 500, maxRetries = 3) {
try {
this.baseConfig = await OssConfigService.fetchBaseConfig()
await this.ensureApiConfig(bucketName, custAttrObj.systemSource)
const fileName = file.name
const client = new OSS({
accessKeyId: this.apiBaseConfig.accessKeyId,
accessKeySecret: this.apiBaseConfig.accessKeySecret,
stsToken: this.apiBaseConfig.securityToken,
bucket: this.baseConfig.alyOss.bucket || bucketName,
endpoint: this.baseConfig.alyOss.endpoint
})
if (partSize < 100) {
throw new Error('分片大小不能小于100KB')
}
// 确保目录以斜杠结尾
const normalizedDir = dir.endsWith('/') ? dir : `${dir}/`
const uniqueDir = `${normalizedDir}${Date.now()}_${Math.floor(Math.random() * 10000)}/`
const key = `${uniqueDir}${fileName}`
let retryCount = 0
let currentCheckpoint = null
const uploadWithRetry = async () => {
try {
const result = await client.multipartUpload(key, file, {
partSize: partSize * 1024,
checkpoint: currentCheckpoint,
progress: (p, checkpoint) => {
currentCheckpoint = checkpoint
console.log(`上传进度: ${(p * 100).toFixed(2)}%`)
}
})
const size = file.size > 1000000 ? `${(file.size / 1000000).toFixed(2)}M` : `${(file.size / 1000).toFixed(2)}KB`
const [aliyunAddress] = result.res.requestUrls
const url = aliyunAddress.split('?')[0].split('https:')[1]
const encodedUrl = this.encodeOSSFilename(decodeURIComponent(url))
successCallback({
attachment: fileName,
aliyunAddress:
"https:" + encodeOSSFilename(decodeURIComponent(url)),
size: size
aliyunAddress: `https:${encodedUrl}`,
size
})
})
.catch((err) => {
console.error("分片上传失败", err)
} catch (err) {
console.error('分片上传失败', err)
if (retryCount < maxRetries) {
retryCount++
console.log(`第${retryCount}次重试上传...`)
setTimeout(() => {
uploadWithRetry()
}, 3000) // 3秒后重试
} else {
errCallBack(err)
await new Promise(resolve => setTimeout(resolve, 3000))
return uploadWithRetry()
}
})
}
const encodeOSSFilename = (filename) => {
// 定义需要转码的特殊字符(包括空格)
const specialChars = '? \\ * | " < > [ ] { } % # & + = ^ ` ~ ; '
// 创建正则表达式匹配所有特殊字符
const escapeRegex = new RegExp(
`[${specialChars.replace(/ /g, "").replace(/(.)/g, "\\$1")}]`,
"g"
)
throw err
}
}
// 转码函数:将字符转为百分号编码
return filename.replace(escapeRegex, (char) => {
// 获取字符的UTF-8编码
const code = char.charCodeAt(0)
// 空格特殊处理为%20,其他转为大写十六进制
return code === 32 ? "%20" : `%${code.toString(16).toUpperCase()}`
})
await uploadWithRetry()
} catch (error) {
console.error('文件上传过程中出错:', error)
errCallBack(error)
}
uploadWithRetry() // 启动上传流程
}
/**
* 编码OSS文件名中的特殊字符
* @param {string} filename 文件名
* @returns {string} 编码后的文件名
*/
encodeOSSFilename(filename) {
const specialChars = '? \\ * | " < > [ ] { } % # & + = ^ ` ~ ; '
const escapeRegex = new RegExp(`[${specialChars.replace(/ /g, '').replace(/(.)/g, '\\$1')}]`, 'g')
return filename.replace(escapeRegex, char => {
const code = char.charCodeAt(0)
return code === 32 ? '%20' : `%${code.toString(16).toUpperCase()}`
})
}
}
export default GlOssApi
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!