index.js
5.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import OSS from 'ali-oss'
import OssConfigService from '../api/ossConfigService' // 导入配置服务
class GlOssApi {
constructor(params = {}) {
this.baseConfig = null
this.defaultImageProcess = params?.defaultImageProcess ?? null
this.addTimestamp = params?.addTimestamp ?? true
}
/**
* 生成上传使用的文件名
* @param {string} fileName 原始文件名
* @returns {string} 上传文件名
*/
getUploadFileName(fileName) {
if (!this.addTimestamp) {
return fileName
}
const extensionIndex = fileName.lastIndexOf('.')
return extensionIndex > 0
? `${fileName.slice(0, extensionIndex)}_${Date.now()}${fileName.slice(extensionIndex)}`
: `${fileName}_${Date.now()}`
}
/**
* 确保获取基础配置(如果尚未获取)
* @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次)
* @param {string|null} imageProcess OSS图片处理参数(可选),例如:'image/format,png'。传null表示不拼接x-oss-process
*/
async multipartUpload(file, successCallback = () => {}, errCallBack = () => {}, bucketName = 'zzl-filerepostorypublic', dir = 'image', custAttrObj = { systemSource: 'dj' }, compressObj = {}, partSize = 500, maxRetries = 3, imageProcess = null) {
try {
// 获取基础配置并动态设置baseURL到httpClient
this.baseConfig = await OssConfigService.fetchBaseConfig()
await this.ensureApiConfig(this.baseConfig?.alyOss?.bucket || bucketName, custAttrObj?.systemSource)
const fileName = this.getUploadFileName(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))
const finalImageProcess = imageProcess ?? this.defaultImageProcess
const publicUrl = `https:${encodedUrl}`
const processedUrl = finalImageProcess
? `${publicUrl}?x-oss-process=${encodeURIComponent(finalImageProcess)}`
: publicUrl
successCallback({
attachment: fileName,
aliyunAddress: processedUrl,
size
})
} catch (err) {
console.error('分片上传失败', err)
if (retryCount < maxRetries) {
retryCount++
console.log(`第${retryCount}次重试上传...`)
await new Promise(resolve => setTimeout(resolve, 3000))
return uploadWithRetry()
}
throw err
}
}
await uploadWithRetry()
} catch (error) {
console.error('文件上传过程中出错:', error)
errCallBack(error)
}
}
/**
* 编码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