@sadais/uploader 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.es.js +417 -0
- package/dist/index.min.js +1 -0
- package/package.json +1 -1
package/dist/index.es.js
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* @Author: fuwenlong
|
|
3
|
+
* @Date: 2022-01-14 14:22:39
|
|
4
|
+
* @LastEditTime: 2024-02-23 16:26:05
|
|
5
|
+
* @LastEditors: zhangzhenfei
|
|
6
|
+
* @Description: 文件上传
|
|
7
|
+
*/
|
|
8
|
+
// 对象存储类型
|
|
9
|
+
const UPLOADER_TYPE = {
|
|
10
|
+
ALIYUN: 'ALIYUN', // 阿里云
|
|
11
|
+
TXYUN: 'TXYUN', // 腾讯云
|
|
12
|
+
HUAWEI: 'HUAWEI' // 华为云
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const DEFAULT_OPTIONS = {
|
|
16
|
+
// type: UPLOADER_TYPE.ALIYUN, //
|
|
17
|
+
// accessKeyId: 'LTAIXeOzClQBtKs3',
|
|
18
|
+
// bucketName: 'sadais-oss',
|
|
19
|
+
// endPoint: 'https://oss-cn-hangzhou.aliyuncs.com',
|
|
20
|
+
// path: 'file',
|
|
21
|
+
// signature: '6Y5l5k56y9VgxDU1vhsyCLC99QM=',
|
|
22
|
+
// domain: 'https://m.antibao.cn',
|
|
23
|
+
// policy:'',
|
|
24
|
+
// timeOut: 1642476191415
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {String} params.type
|
|
29
|
+
* @param {String} params.getOptionFun
|
|
30
|
+
*/
|
|
31
|
+
const UploaderInstance = (function () {
|
|
32
|
+
let instance;
|
|
33
|
+
return function (params) {
|
|
34
|
+
if (!instance) {
|
|
35
|
+
instance = new SadaisUploader(params);
|
|
36
|
+
}
|
|
37
|
+
return instance
|
|
38
|
+
}
|
|
39
|
+
})();
|
|
40
|
+
|
|
41
|
+
class SadaisUploader {
|
|
42
|
+
constructor(params) {
|
|
43
|
+
this._init(params);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 初始化
|
|
48
|
+
* @param {Object} options
|
|
49
|
+
*/
|
|
50
|
+
async _init(params) {
|
|
51
|
+
this.params = params;
|
|
52
|
+
// 不在初始化的时候调用接口,上传文件时再调用,故注释以下代码
|
|
53
|
+
// this._initOptions()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 获取配置信息
|
|
58
|
+
*/
|
|
59
|
+
async initOptions(customParams) {
|
|
60
|
+
if (!this.params) this.params = {};
|
|
61
|
+
|
|
62
|
+
if (customParams) {
|
|
63
|
+
return (this.params = {
|
|
64
|
+
...this.params,
|
|
65
|
+
...customParams
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
let { type, getOptionFun, path, getAuthInfoFunc, isUploadWebp } = this.params;
|
|
69
|
+
this.getAuthInfoFunc = getAuthInfoFunc;
|
|
70
|
+
this.options = { type, isUploadWebp };
|
|
71
|
+
if (getOptionFun) {
|
|
72
|
+
const options = await getOptionFun(type);
|
|
73
|
+
if (!options) return
|
|
74
|
+
path = path || options.path;
|
|
75
|
+
if (path && !path.endsWith('/')) {
|
|
76
|
+
options.path = path + '/';
|
|
77
|
+
}
|
|
78
|
+
this.options = { ...this.options, ...options };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 是否超时
|
|
84
|
+
*/
|
|
85
|
+
_isTimeOut() {
|
|
86
|
+
// 比服务器timeOut时间提前10s过期
|
|
87
|
+
const timeout = this.options.timeOut - 1000 * 10;
|
|
88
|
+
return new Date().getTime() > timeout
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 文件上传
|
|
93
|
+
* @param { File | Array<file> } file 文件或文件数组
|
|
94
|
+
*/
|
|
95
|
+
async upload(file) {
|
|
96
|
+
if (!file) return
|
|
97
|
+
let files = Array.isArray(file) ? file : [file];
|
|
98
|
+
const result = [];
|
|
99
|
+
for (let i = 0; i < files.length; i++) {
|
|
100
|
+
const item = files[i];
|
|
101
|
+
const { data, head } = await this.uploadFile(item);
|
|
102
|
+
result.push({
|
|
103
|
+
index: i,
|
|
104
|
+
url: data,
|
|
105
|
+
ret: head.ret
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
return result
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 单文件上传
|
|
113
|
+
* @param {File} file
|
|
114
|
+
* @return Promise
|
|
115
|
+
*/
|
|
116
|
+
async uploadFile(file, opts = {}) {
|
|
117
|
+
if (!this.options || this._isTimeOut()) {
|
|
118
|
+
await this.initOptions();
|
|
119
|
+
}
|
|
120
|
+
this.options = {
|
|
121
|
+
...this.options,
|
|
122
|
+
...opts
|
|
123
|
+
};
|
|
124
|
+
if (!file.name && file.path) {
|
|
125
|
+
const isBlobFile = file.path.startsWith('blob');
|
|
126
|
+
const isBase64File = file.path.startsWith('data');
|
|
127
|
+
const suffix =
|
|
128
|
+
isBlobFile || isBase64File ? '.png' : file.path.substring(file.path.lastIndexOf('.'));
|
|
129
|
+
file.name = this._guid() + suffix;
|
|
130
|
+
}
|
|
131
|
+
return new Promise((resolve, reject) => {
|
|
132
|
+
if (
|
|
133
|
+
this.options.isUploadWebp &&
|
|
134
|
+
UPLOADER_TYPE.TXYUN == this.params.type &&
|
|
135
|
+
this._fileIsPic(file.name)
|
|
136
|
+
) {
|
|
137
|
+
// 腾讯云使用put上传
|
|
138
|
+
this._putSubmit(resolve, reject, file);
|
|
139
|
+
} else {
|
|
140
|
+
this._formSubmit(resolve, reject, file);
|
|
141
|
+
}
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 多文件上传
|
|
147
|
+
* @param {Array<File>} files
|
|
148
|
+
* @return Promise
|
|
149
|
+
*/
|
|
150
|
+
async uploadFiles(files, opts = {}) {
|
|
151
|
+
const successUrls = [];
|
|
152
|
+
const failUrls = [];
|
|
153
|
+
for (const file of files) {
|
|
154
|
+
const { data, head } = await this.uploadFile(file, opts);
|
|
155
|
+
if (head.ret === 0) {
|
|
156
|
+
successUrls.push(data);
|
|
157
|
+
} else {
|
|
158
|
+
failUrls.push(data);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return { successUrls, failUrls }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// 表单上传
|
|
165
|
+
_formSubmit(resolve, reject, file) {
|
|
166
|
+
console.log('表单上传');
|
|
167
|
+
const { domain } = this.options;
|
|
168
|
+
|
|
169
|
+
// 请求地址
|
|
170
|
+
const formData = this._buildParams(file);
|
|
171
|
+
|
|
172
|
+
const apiUrl = formData.url;
|
|
173
|
+
const uploadedFilePath = `${domain}${domain.endsWith('/') ? '' : '/'}${formData.key}`;
|
|
174
|
+
const success = {
|
|
175
|
+
data: uploadedFilePath,
|
|
176
|
+
head: { ret: 0, msg: 'success' }
|
|
177
|
+
};
|
|
178
|
+
const error = {
|
|
179
|
+
data: file.name,
|
|
180
|
+
head: { ret: 1, msg: 'fail' }
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
try {
|
|
184
|
+
// uniapp
|
|
185
|
+
uni.uploadFile({
|
|
186
|
+
url: apiUrl,
|
|
187
|
+
filePath: file.path, // uni api提供的blob格式图片地址
|
|
188
|
+
name: 'file',
|
|
189
|
+
formData,
|
|
190
|
+
success: (res) => {
|
|
191
|
+
const { statusCode } = res;
|
|
192
|
+
if (statusCode == 200) {
|
|
193
|
+
resolve(success);
|
|
194
|
+
} else {
|
|
195
|
+
error.head.msg = res;
|
|
196
|
+
reject(error);
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
fail: (error) => {
|
|
200
|
+
console.log(error);
|
|
201
|
+
reject(error);
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
// H5 input:file接收内容
|
|
205
|
+
} catch (e) {
|
|
206
|
+
console.log('uni报错,调用XMLHttpRequest', e);
|
|
207
|
+
const data = new FormData();
|
|
208
|
+
Object.keys(formData).forEach((key) => {
|
|
209
|
+
data.append(key, formData[key]);
|
|
210
|
+
});
|
|
211
|
+
data.append('file', file);
|
|
212
|
+
const xhr = new XMLHttpRequest();
|
|
213
|
+
xhr.open('POST', apiUrl, true);
|
|
214
|
+
xhr.onreadystatechange = () => {
|
|
215
|
+
if (xhr.readyState === XMLHttpRequest.DONE) {
|
|
216
|
+
if (xhr.status === 200) {
|
|
217
|
+
resolve(success);
|
|
218
|
+
} else {
|
|
219
|
+
reject(error);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
xhr.send(data);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// 腾讯put上传
|
|
228
|
+
async _putSubmit(resolve, reject, file) {
|
|
229
|
+
const { domain } = this.options;
|
|
230
|
+
|
|
231
|
+
const formData = this._buildParams(file);
|
|
232
|
+
const apiUrl = formData.url + '/' + formData.key;
|
|
233
|
+
|
|
234
|
+
// watermark/2/text/6IW-6K6v5LqRwrfkuIfosaHkvJjlm74/fill/IzNEM0QzRA/fontsize/20/dissolve/50/gravity/northeast/dx/20/dy/20/batch/1/degree/45|
|
|
235
|
+
const picOperations = JSON.stringify({
|
|
236
|
+
is_pic_info: 1,
|
|
237
|
+
rules: [
|
|
238
|
+
{
|
|
239
|
+
fileid: '/' + formData.key,
|
|
240
|
+
rule: 'imageMogr2/format/webp'
|
|
241
|
+
}
|
|
242
|
+
]
|
|
243
|
+
});
|
|
244
|
+
const authParams = {
|
|
245
|
+
httpMethodName: 'PUT',
|
|
246
|
+
resoucePath: '/' + formData.key,
|
|
247
|
+
storage: this.params.type,
|
|
248
|
+
headerMap: {
|
|
249
|
+
'Pic-Operations': picOperations
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
const authInfo = await this.getAuthInfoFunc(authParams);
|
|
253
|
+
const authorizationInfo = authInfo ? authInfo.content : '';
|
|
254
|
+
if (!authorizationInfo) return reject(error)
|
|
255
|
+
const uploadedFilePath = `${domain}${domain.endsWith('/') ? '' : '/'}${formData.key}`;
|
|
256
|
+
const success = {
|
|
257
|
+
data: uploadedFilePath,
|
|
258
|
+
head: { ret: 0, msg: 'success' }
|
|
259
|
+
};
|
|
260
|
+
const error = {
|
|
261
|
+
data: file.name,
|
|
262
|
+
head: { ret: 1, msg: 'fail' }
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
const uploadFunc = (data) => {
|
|
266
|
+
try {
|
|
267
|
+
uni.request({
|
|
268
|
+
url: apiUrl,
|
|
269
|
+
method: 'PUT',
|
|
270
|
+
data,
|
|
271
|
+
header: {
|
|
272
|
+
'Authorization': authorizationInfo,
|
|
273
|
+
'Pic-Operations': picOperations
|
|
274
|
+
},
|
|
275
|
+
success: (res) => {
|
|
276
|
+
const { statusCode } = res;
|
|
277
|
+
if (statusCode == 200) {
|
|
278
|
+
resolve(success);
|
|
279
|
+
} else {
|
|
280
|
+
error.head.msg = res;
|
|
281
|
+
reject(error);
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
fail: (error) => {
|
|
285
|
+
console.log(error);
|
|
286
|
+
reject(error);
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
} catch (e) {
|
|
290
|
+
console.log('web环境');
|
|
291
|
+
const xhr = new XMLHttpRequest();
|
|
292
|
+
xhr.open('PUT', apiUrl, true);
|
|
293
|
+
xhr.setRequestHeader('Authorization', authorizationInfo);
|
|
294
|
+
xhr.setRequestHeader('Pic-Operations', picOperations);
|
|
295
|
+
xhr.onreadystatechange = () => {
|
|
296
|
+
if (xhr.readyState === XMLHttpRequest.DONE) {
|
|
297
|
+
if (xhr.status === 200) {
|
|
298
|
+
resolve(success);
|
|
299
|
+
} else {
|
|
300
|
+
reject(error);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
xhr.send(data);
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
try {
|
|
308
|
+
console.log('微信环境');
|
|
309
|
+
const fileManager = uni.getFileSystemManager();
|
|
310
|
+
const fileData = fileManager.readFileSync(file.path);
|
|
311
|
+
uploadFunc(fileData);
|
|
312
|
+
} catch (e) {
|
|
313
|
+
console.log('H5环境');
|
|
314
|
+
if (file.type) {
|
|
315
|
+
uploadFunc(file);
|
|
316
|
+
} else {
|
|
317
|
+
const fileObj = await fetch(file.path).then((r) => r.blob());
|
|
318
|
+
const reader = new FileReader();
|
|
319
|
+
reader.onload = function () {
|
|
320
|
+
uploadFunc(reader.result);
|
|
321
|
+
};
|
|
322
|
+
reader.readAsArrayBuffer(fileObj);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
_fileIsPic(name) {
|
|
328
|
+
const suffix = name.substring(name.lastIndexOf('.') + 1);
|
|
329
|
+
const suffixs = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'avif', 'heif', 'tpg', 'psd'];
|
|
330
|
+
return suffixs.includes(suffix.toLowerCase())
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// 按类型组装过参数
|
|
334
|
+
_buildParams(file) {
|
|
335
|
+
const opt = this.options;
|
|
336
|
+
const type = opt.type;
|
|
337
|
+
const params = {
|
|
338
|
+
name: file.name,
|
|
339
|
+
policy: opt.policy,
|
|
340
|
+
success_action_status: '200',
|
|
341
|
+
key: this._getUploadFilePath(file.name)
|
|
342
|
+
};
|
|
343
|
+
const endPoint = opt.endPoint.replace('https://', '').replace('http://', '');
|
|
344
|
+
if (UPLOADER_TYPE.TXYUN === type) {
|
|
345
|
+
params['q-ak'] = opt.accessKeyId;
|
|
346
|
+
params['q-signature'] = opt.signature; // 签名
|
|
347
|
+
params['q-sign-algorithm'] = 'sha1'; // 签名算法
|
|
348
|
+
params['q-key-time'] = opt.param['q-sign-time'];
|
|
349
|
+
params.url = `https://${opt.bucketName}.cos.${endPoint}.myqcloud.com`;
|
|
350
|
+
} else if (UPLOADER_TYPE.HUAWEI === type) {
|
|
351
|
+
params.AccessKeyId = opt.accessKeyId;
|
|
352
|
+
params.signature = opt.signature;
|
|
353
|
+
params.url = `https://${opt.bucketName}.obs.${endPoint}.myhuaweicloud.com`;
|
|
354
|
+
} else {
|
|
355
|
+
params.signature = opt.signature;
|
|
356
|
+
params.OSSAccessKeyId = opt.accessKeyId;
|
|
357
|
+
params.bucket = opt.bucketName;
|
|
358
|
+
|
|
359
|
+
params.url = `https://${opt.bucketName}.${endPoint}`;
|
|
360
|
+
}
|
|
361
|
+
return params
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* 获取上传文件路径
|
|
366
|
+
* @param {String} name 文件名
|
|
367
|
+
* @returns
|
|
368
|
+
*/
|
|
369
|
+
_getUploadFilePath(name) {
|
|
370
|
+
this.params.type;
|
|
371
|
+
const { useOriginalName, path } = this.options;
|
|
372
|
+
const lastIndexOf = name.lastIndexOf('.');
|
|
373
|
+
const originalName = name.substring(0, lastIndexOf);
|
|
374
|
+
let suffix = name.substring(lastIndexOf + 1);
|
|
375
|
+
// 腾讯云上传图片固定为webp格式
|
|
376
|
+
// if (UPLOADER_TYPE.TXYUN == type && this._fileIsPic(name)) {
|
|
377
|
+
// suffix = 'webp'
|
|
378
|
+
// }
|
|
379
|
+
const fileName = useOriginalName ? `/${originalName}` : '';
|
|
380
|
+
// 为了保证使用文件原名时,文件不被覆盖,仍然使用随机生成方式
|
|
381
|
+
// ${this._getNowDate()}/
|
|
382
|
+
return `${path}${this._getNowDate()}/${this._guid()}${fileName}.${suffix}`
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* 获取当前日期
|
|
387
|
+
* @returns YYYY-MM-DD
|
|
388
|
+
*/
|
|
389
|
+
_getNowDate() {
|
|
390
|
+
const date = new Date();
|
|
391
|
+
const year = date.getFullYear();
|
|
392
|
+
let month = date.getMonth() + 1;
|
|
393
|
+
let day = date.getDate();
|
|
394
|
+
if (month < 10) {
|
|
395
|
+
month = `0${month}`;
|
|
396
|
+
}
|
|
397
|
+
if (day < 10) {
|
|
398
|
+
day = `0${day}`;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
return `${year}${month}${day}`
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* 生成guid,用于生成随机文件名
|
|
406
|
+
* @return String
|
|
407
|
+
*/
|
|
408
|
+
_guid() {
|
|
409
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
|
410
|
+
var r = (Math.random() * 16) | 0,
|
|
411
|
+
v = c == 'x' ? r : (r & 0x3) | 0x8;
|
|
412
|
+
return v.toString(16)
|
|
413
|
+
})
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export { DEFAULT_OPTIONS, UPLOADER_TYPE, UploaderInstance };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";function e(e,n){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,n){if(!e)return;if("string"==typeof e)return t(e,n);var r=Object.prototype.toString.call(e).slice(8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return Array.from(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return t(e,n)}(e))||n&&e&&"number"==typeof e.length){r&&(e=r);var a=0,i=function(){};return{s:i,n:function(){return a>=e.length?{done:!0}:{done:!1,value:e[a++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,u=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){u=!0,o=e},f:function(){try{s||null==r.return||r.return()}finally{if(u)throw o}}}}function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function r(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?n(Object(r),!0).forEach((function(t){a(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t,n,r,a,i,o){try{var s=e[i](o),u=s.value}catch(e){return void n(e)}s.done?t(u):Promise.resolve(u).then(r,a)}function o(e){return function(){var t=this,n=arguments;return new Promise((function(r,a){var o=e.apply(t,n);function s(e){i(o,r,a,s,u,"next",e)}function u(e){i(o,r,a,s,u,"throw",e)}s(void 0)}))}}function s(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}Object.defineProperty(exports,"__esModule",{value:!0});var u,c={ALIYUN:"ALIYUN",TXYUN:"TXYUN",HUAWEI:"HUAWEI"},p=function(e){return u||(u=new l(e)),u},l=function(){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),this._init(e)}var n,a,i,u,p,l,f,h,d;return n=t,a=[{key:"_init",value:(d=o(regeneratorRuntime.mark((function e(t){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.params=t;case 1:case"end":return e.stop()}}),e,this)}))),function(e){return d.apply(this,arguments)})},{key:"initOptions",value:(h=o(regeneratorRuntime.mark((function e(t){var n,a,i,o,s,u,c;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.params||(this.params={}),!t){e.next=3;break}return e.abrupt("return",this.params=r(r({},this.params),t));case 3:if(n=this.params,a=n.type,i=n.getOptionFun,o=n.path,s=n.getAuthInfoFunc,u=n.isUploadWebp,this.getAuthInfoFunc=s,this.options={type:a,isUploadWebp:u},!i){e.next=15;break}return e.next=9,i(a);case 9:if(c=e.sent){e.next=12;break}return e.abrupt("return");case 12:(o=o||c.path)&&!o.endsWith("/")&&(c.path=o+"/"),this.options=r(r({},this.options),c);case 15:case"end":return e.stop()}}),e,this)}))),function(e){return h.apply(this,arguments)})},{key:"_isTimeOut",value:function(){var e=this.options.timeOut-1e4;return(new Date).getTime()>e}},{key:"upload",value:(f=o(regeneratorRuntime.mark((function e(t){var n,r,a,i,o,s,u;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t){e.next=2;break}return e.abrupt("return");case 2:n=Array.isArray(t)?t:[t],r=[],a=0;case 5:if(!(a<n.length)){e.next=16;break}return i=n[a],e.next=9,this.uploadFile(i);case 9:o=e.sent,s=o.data,u=o.head,r.push({index:a,url:s,ret:u.ret});case 13:a++,e.next=5;break;case 16:return e.abrupt("return",r);case 17:case"end":return e.stop()}}),e,this)}))),function(e){return f.apply(this,arguments)})},{key:"uploadFile",value:(l=o(regeneratorRuntime.mark((function e(t){var n,a,i,o,s=this,u=arguments;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=u.length>1&&void 0!==u[1]?u[1]:{},this.options&&!this._isTimeOut()){e.next=4;break}return e.next=4,this.initOptions();case 4:return this.options=r(r({},this.options),n),!t.name&&t.path&&(a=t.path.startsWith("blob"),i=t.path.startsWith("data"),o=a||i?".png":t.path.substring(t.path.lastIndexOf(".")),t.name=this._guid()+o),e.abrupt("return",new Promise((function(e,n){s.options.isUploadWebp&&c.TXYUN==s.params.type&&s._fileIsPic(t.name)?s._putSubmit(e,n,t):s._formSubmit(e,n,t)})));case 7:case"end":return e.stop()}}),e,this)}))),function(e){return l.apply(this,arguments)})},{key:"uploadFiles",value:(p=o(regeneratorRuntime.mark((function t(n){var r,a,i,o,s,u,c,p,l=arguments;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:r=l.length>1&&void 0!==l[1]?l[1]:{},a=[],i=[],o=e(n),t.prev=4,o.s();case 6:if((s=o.n()).done){t.next=16;break}return u=s.value,t.next=10,this.uploadFile(u,r);case 10:c=t.sent,p=c.data,0===c.head.ret?a.push(p):i.push(p);case 14:t.next=6;break;case 16:t.next=21;break;case 18:t.prev=18,t.t0=t.catch(4),o.e(t.t0);case 21:return t.prev=21,o.f(),t.finish(21);case 24:return t.abrupt("return",{successUrls:a,failUrls:i});case 25:case"end":return t.stop()}}),t,this,[[4,18,21,24]])}))),function(e){return p.apply(this,arguments)})},{key:"_formSubmit",value:function(e,t,n){console.log("表单上传");var r=this.options.domain,a=this._buildParams(n),i=a.url,o={data:"".concat(r).concat(r.endsWith("/")?"":"/").concat(a.key),head:{ret:0,msg:"success"}},s={data:n.name,head:{ret:1,msg:"fail"}};try{uni.uploadFile({url:i,filePath:n.path,name:"file",formData:a,success:function(n){200==n.statusCode?e(o):(s.head.msg=n,t(s))},fail:function(e){console.log(e),t(e)}})}catch(r){console.log("uni报错,调用XMLHttpRequest",r);var u=new FormData;Object.keys(a).forEach((function(e){u.append(e,a[e])})),u.append("file",n);var c=new XMLHttpRequest;c.open("POST",i,!0),c.onreadystatechange=function(){c.readyState===XMLHttpRequest.DONE&&(200===c.status?e(o):t(s))},c.send(u)}}},{key:"_putSubmit",value:(u=o(regeneratorRuntime.mark((function e(t,n,r){var a,i,o,s,u,c,p,l,f,h,d,m,y,g,b;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=this.options.domain,i=this._buildParams(r),o=i.url+"/"+i.key,s=JSON.stringify({is_pic_info:1,rules:[{fileid:"/"+i.key,rule:"imageMogr2/format/webp"}]}),u={httpMethodName:"PUT",resoucePath:"/"+i.key,storage:this.params.type,headerMap:{"Pic-Operations":s}},e.next=7,this.getAuthInfoFunc(u);case 7:if(c=e.sent,p=c?c.content:""){e.next=11;break}return e.abrupt("return",n(h));case 11:l="".concat(a).concat(a.endsWith("/")?"":"/").concat(i.key),f={data:l,head:{ret:0,msg:"success"}},h={data:r.name,head:{ret:1,msg:"fail"}},d=function(e){try{uni.request({url:o,method:"PUT",data:e,header:{Authorization:p,"Pic-Operations":s},success:function(e){200==e.statusCode?t(f):(h.head.msg=e,n(h))},fail:function(e){console.log(e),n(e)}})}catch(a){console.log("web环境");var r=new XMLHttpRequest;r.open("PUT",o,!0),r.setRequestHeader("Authorization",p),r.setRequestHeader("Pic-Operations",s),r.onreadystatechange=function(){r.readyState===XMLHttpRequest.DONE&&(200===r.status?t(f):n(h))},r.send(e)}},e.prev=15,console.log("微信环境"),m=uni.getFileSystemManager(),y=m.readFileSync(r.path),d(y),e.next=35;break;case 22:if(e.prev=22,e.t0=e.catch(15),console.log("H5环境"),!r.type){e.next=29;break}d(r),e.next=35;break;case 29:return e.next=31,fetch(r.path).then((function(e){return e.blob()}));case 31:g=e.sent,(b=new FileReader).onload=function(){d(b.result)},b.readAsArrayBuffer(g);case 35:case"end":return e.stop()}}),e,this,[[15,22]])}))),function(e,t,n){return u.apply(this,arguments)})},{key:"_fileIsPic",value:function(e){var t=e.substring(e.lastIndexOf(".")+1);return["png","jpg","jpeg","gif","bmp","webp","avif","heif","tpg","psd"].includes(t.toLowerCase())}},{key:"_buildParams",value:function(e){var t=this.options,n=t.type,r={name:e.name,policy:t.policy,success_action_status:"200",key:this._getUploadFilePath(e.name)},a=t.endPoint.replace("https://","").replace("http://","");return c.TXYUN===n?(r["q-ak"]=t.accessKeyId,r["q-signature"]=t.signature,r["q-sign-algorithm"]="sha1",r["q-key-time"]=t.param["q-sign-time"],r.url="https://".concat(t.bucketName,".cos.").concat(a,".myqcloud.com")):c.HUAWEI===n?(r.AccessKeyId=t.accessKeyId,r.signature=t.signature,r.url="https://".concat(t.bucketName,".obs.").concat(a,".myhuaweicloud.com")):(r.signature=t.signature,r.OSSAccessKeyId=t.accessKeyId,r.bucket=t.bucketName,r.url="https://".concat(t.bucketName,".").concat(a)),r}},{key:"_getUploadFilePath",value:function(e){this.params.type;var t=this.options,n=t.useOriginalName,r=t.path,a=e.lastIndexOf("."),i=e.substring(0,a),o=e.substring(a+1),s=n?"/".concat(i):"";return"".concat(r).concat(this._getNowDate(),"/").concat(this._guid()).concat(s,".").concat(o)}},{key:"_getNowDate",value:function(){var e=new Date,t=e.getFullYear(),n=e.getMonth()+1,r=e.getDate();return n<10&&(n="0".concat(n)),r<10&&(r="0".concat(r)),"".concat(t).concat(n).concat(r)}},{key:"_guid",value:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}}],a&&s(n.prototype,a),i&&s(n,i),Object.defineProperty(n,"prototype",{writable:!1}),t}();exports.DEFAULT_OPTIONS={},exports.UPLOADER_TYPE=c,exports.UploaderInstance=p;
|