oss.js
3.4 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
const OSS = require("ali-oss")
class GlOssApi {
constructor(params = {}) {
this.baseConfig = params.baseConfig
}
/**
* 分片上传大文件到阿里云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.alyOss.accessKeyId,
accessKeySecret: baseConfig.alyOss.accessKeySecret,
bucket: baseConfig.alyOss.bucket,
endpoint: baseConfig.alyOss.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 = async () => {
client
.multipartUpload(key, file, {
partSize: partSize * 1024, // 转换为字节
checkpoint: currentCheckpoint, // 使用上次的断点信息
progress: function (p, checkpoint) {
currentCheckpoint = checkpoint
console.log(`上传进度: ${p * 100}%`)
}
})
.then(async (result) => {
const size =
file.size > 1000000
? parseFloat(file.size / 1000000).toFixed(2) + "M"
: parseFloat(file.size / 1000).toFixed(2) + "KB"
console.log(result, 111111111)
let [aliyunAddress] = result.res.requestUrls
console.log(aliyunAddress, "aliyunAddress")
const sourceImage = aliyunAddress
const targetImage = "exampledir/dest.png"
await processImage(
"image/quality,Q_50",
bucketName,
result.name,
targetImage
)
successCallback({
attachment: fileName,
aliyunAddress: decodeURIComponent(aliyunAddress).split("?")[0],
size: size
})
})
.catch((err) => {
console.error("分片上传失败", err)
if (retryCount < maxRetries) {
retryCount++
console.log(`第${retryCount}次重试上传...`)
setTimeout(() => {
uploadWithRetry()
}, 3000) // 3秒后重试
} else {
errCallBack(err)
}
})
}
const processImage = async (
processStr,
targetBucket,
sourceImage,
targetImage
) => {
const result = await client.processObjectSave(
sourceImage,
targetImage,
processStr,
targetBucket
)
console.log(result.res, "99999")
}
uploadWithRetry() // 启动上传流程
}
}
export default GlOssApi