index.html
3.11 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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title></title>
</head>
<style>
body,
html {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background: rgb(0, 0, 0, 0.5);
}
.loading {
width: 50px;
height: 50px;
border: 3px solid #666;
border-radius: 50%;
border-top-color: #fff;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<div class="loading"></div>
<script src="js/uni.webview.1.5.5.js"></script>
<script src="js/aliyun-oss-sdk-6.18.1.min.js"></script>
<script src="js/OSSUpLoader.js"></script>
<script>
// document.addEventListener('UniAppJSBridgeReady', function(){
/**
* 该函数用于接收来自 UniApp 的消息,它包含了文件上传所需的所有信息
* @param {string} accessKeyId - OSS 访问密钥 ID
* @param {string} accessKeySecret - OSS 访问密钥 secret
* @param {string} stsToken - 安全令牌服务(STS)令牌,用于临时访问 OSS 存储桶
* @param {string} fileName - 要上传的文件名
* @param {string} filePath - 要上传的文件所在路径
* @param {string} recordId - 与上传文件相关联的记录ID
* @param {Object} options - (可选)包含上传器配置的对象,如 region
* @throws {Error} 如果缺少必要的参数,将抛出错误
*/
window.msgFromUniapp = function (accessKeyId, accessKeySecret, stsToken, fileName, filePath, recordId, options = {}) {
try {
if (!accessKeyId || !accessKeySecret || !stsToken || !fileName || !filePath) {
throw new Error('accessKeyId,accessKeySecret,stsToken,fileName,filePath is required')
}
// 使用 Object.assign 合并默认配置参数和传入的 options 参数
const opt = Object.assign({ accessKeyId, accessKeySecret, stsToken, filePath, recordId }, options)
// 创建 OSSUpLoader 实例,传入配置对象
let uploader = new OSSUpLoader(opt)
// 调用 upload 方法上传文件,并在完成后处理结果
uploader.upload(fileName, function (result) {
// 通过 uni.postMessage 将上传结果作为数据发送
uni.postMessage({
data: {
...result,
fileName,
recordId,
filePath,
accessKeyId
}
})
// 调用 destroy 方法,这将重置上传器的状态,释放资源
uploader.destroy()
// 将 uploader 置为 null,释放内存
uploader = null
})
} catch (e) {
// 如果发生错误,将错误信息作为数据发送
uni.postMessage({
data: {
code: 1,
fileName,
recordId,
filePath,
message: e.message
}
})
}
}
// }, false);
</script>
</body>
</html>