@sadais/uploader 0.4.1 → 0.4.3

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