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