@sadais/uploader 0.4.5 → 0.4.7

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 CHANGED
@@ -1,10 +1,14 @@
1
1
  /*
2
2
  * @Author: fuwenlong
3
3
  * @Date: 2022-01-14 14:22:39
4
- * @LastEditTime: 2024-05-14 15:43:04
4
+ * @LastEditTime: 2024-07-08 15:35:59
5
5
  * @LastEditors: zhangzhenfei
6
6
  * @Description: 文件上传
7
7
  */
8
+ // 初始化 oss 重试机制
9
+ let MaxOssRetry = 10;
10
+ let initOssRetry = 0;
11
+
8
12
  function isFile(obj) {
9
13
  return obj && obj.size
10
14
  }
@@ -17,7 +21,7 @@ const UPLOADER_TYPE = {
17
21
  };
18
22
 
19
23
  const DEFAULT_OPTIONS = {
20
- // type: UPLOADER_TYPE.ALIYUN, //
24
+ // type: UPLOADER_TYPE.ALIYUN,
21
25
  // accessKeyId: 'LTAIXeOzClQBtKs3',
22
26
  // bucketName: 'sadais-oss',
23
27
  // endPoint: 'https://oss-cn-hangzhou.aliyuncs.com',
@@ -69,11 +73,13 @@ class SadaisUploader {
69
73
  ...customParams
70
74
  })
71
75
  }
72
- let { type, getOptionFun, path, getAuthInfoFunc, isUploadWebp } = this.params;
76
+ let { type, getOptionFun, path, getAuthInfoFunc, isUploadWebp, ossFailedApiOption } =
77
+ this.params;
73
78
  this.getAuthInfoFunc = getAuthInfoFunc;
74
- this.options = { type, isUploadWebp };
79
+ this.options = { type, isUploadWebp, ossFailedApiOption };
75
80
  if (getOptionFun) {
76
- const options = await getOptionFun(type);
81
+ initOssRetry = 0;
82
+ const options = await this._initOptionFun();
77
83
  if (!options) return
78
84
  path = path || options.path;
79
85
  if (path && !path.endsWith('/')) {
@@ -83,6 +89,26 @@ class SadaisUploader {
83
89
  }
84
90
  }
85
91
 
92
+ async _initOptionFun() {
93
+ return new Promise((resolve) => {
94
+ const intervalId = setInterval(async () => {
95
+ if (initOssRetry > MaxOssRetry) {
96
+ console.log('oss初始化失败');
97
+ clearInterval(intervalId);
98
+ initOssRetry = 0;
99
+ resolve({});
100
+ }
101
+ console.log('初始化oss重试', initOssRetry);
102
+ initOssRetry++;
103
+ const options = await this.params.getOptionFun(this.params.type);
104
+ if (options?.endPoint) {
105
+ clearInterval(intervalId);
106
+ resolve(options);
107
+ }
108
+ }, 1000);
109
+ })
110
+ }
111
+
86
112
  /**
87
113
  * 是否超时
88
114
  */
@@ -118,7 +144,8 @@ class SadaisUploader {
118
144
  * @return Promise
119
145
  */
120
146
  async uploadFile(file, opts = {}) {
121
- if (!this.options || this._isTimeOut()) {
147
+ if (!this.options || !this.options?.endPoint || this._isTimeOut()) {
148
+ console.log('初始化 oss 开始');
122
149
  await this.initOptions();
123
150
  }
124
151
 
@@ -142,7 +169,11 @@ class SadaisUploader {
142
169
  }
143
170
 
144
171
  return new Promise((resolve, reject) => {
145
- if (
172
+ if (!this.options.endPoint) {
173
+ // oss 初始化失败的情况下,走接口上传
174
+ console.log('oss 初始化失败,走接口上传');
175
+ this._apiSubmit(resolve, reject, file);
176
+ } else if (
146
177
  this.options.isUploadWebp &&
147
178
  UPLOADER_TYPE.TXYUN == this.params.type &&
148
179
  this._fileIsPic(file.name)
@@ -200,6 +231,7 @@ class SadaisUploader {
200
231
  filePath: file.path, // uni api提供的blob格式图片地址
201
232
  name: 'file',
202
233
  formData,
234
+ timeout: this.options.uploadTimeOut || 20000, // 默认20s
203
235
  success: (res) => {
204
236
  const { statusCode } = res;
205
237
  if (statusCode == 200) {
@@ -223,6 +255,7 @@ class SadaisUploader {
223
255
  });
224
256
  data.append('file', file);
225
257
  const xhr = new XMLHttpRequest();
258
+ xhr.timeout = this.options.uploadTimeOut || 20000; // 默认20s
226
259
  xhr.open('POST', apiUrl, true);
227
260
  xhr.onreadystatechange = () => {
228
261
  if (xhr.readyState === XMLHttpRequest.DONE) {
@@ -237,9 +270,50 @@ class SadaisUploader {
237
270
  }
238
271
  }
239
272
 
273
+ async _apiSubmit(resolve, reject, file) {
274
+ console.log('api接口上传');
275
+ const { ossFailedApiOption } = this.options;
276
+
277
+ const success = {
278
+ data: '',
279
+ head: { ret: 0, msg: 'success' }
280
+ };
281
+ const error = {
282
+ data: file.name,
283
+ head: { ret: 1, msg: 'fail' }
284
+ };
285
+
286
+ try {
287
+ const [, result] = await uni.uploadFile({
288
+ url: ossFailedApiOption.api,
289
+ filePath: file.path,
290
+ name: 'file',
291
+ timeout: this.options.uploadTimeOut || 20000 // 默认20s
292
+ });
293
+ console.log('api接口上传结果', result);
294
+
295
+ const { errMsg, data: resData } = result || {};
296
+ if (!errMsg || errMsg !== 'uploadFile:ok') {
297
+ throw new Error(errMsg)
298
+ }
299
+ const { data, head: { ret, msg } = {} } = JSON.parse(resData);
300
+
301
+ if (ret !== ossFailedApiOption.successRetCode) {
302
+ error.head.msg = msg;
303
+ reject(error);
304
+ } else {
305
+ success.data = data.url;
306
+ resolve(success);
307
+ }
308
+ } catch (error) {
309
+ reject(error);
310
+ }
311
+ }
312
+
240
313
  // 腾讯put上传
241
314
  async _putSubmit(resolve, reject, file) {
242
- const { domain } = this.options;
315
+ console.log('腾讯put上传');
316
+ const { domain, ossFailedApiOption } = this.options;
243
317
 
244
318
  const formData = this._buildParams(file);
245
319
  const apiUrl = formData.url + '/' + formData.key;
@@ -262,7 +336,20 @@ class SadaisUploader {
262
336
  'Pic-Operations': picOperations
263
337
  }
264
338
  };
265
- const authInfo = await this.getAuthInfoFunc(authParams);
339
+
340
+ let authInfo = {};
341
+ try {
342
+ console.log('获取权限信息');
343
+ authInfo = await this.getAuthInfoFunc(authParams);
344
+ console.log('获取权限结果', authInfo);
345
+ if (!authInfo.content) {
346
+ return this._apiSubmit(resolve, reject, file)
347
+ }
348
+ } catch (error) {
349
+ console.log('获取权限失败', error);
350
+ return this._apiSubmit(resolve, reject, file)
351
+ }
352
+
266
353
  const authorizationInfo = authInfo ? authInfo.content : '';
267
354
  if (!authorizationInfo) return reject(error)
268
355
  const uploadedFilePath = `${domain}${domain.endsWith('/') ? '' : '/'}${formData.key}`;
@@ -276,6 +363,7 @@ class SadaisUploader {
276
363
  };
277
364
 
278
365
  const uploadFunc = (data) => {
366
+ console.log('上传数据', data);
279
367
  try {
280
368
  uni.request({
281
369
  url: apiUrl,
@@ -285,18 +373,29 @@ class SadaisUploader {
285
373
  'Authorization': authorizationInfo,
286
374
  'Pic-Operations': picOperations
287
375
  },
376
+ timeout: this.options.uploadTimeOut || 20000, // 默认20s
288
377
  success: (res) => {
378
+ console.log('上传结果', res);
289
379
  const { statusCode } = res;
290
380
  if (statusCode == 200) {
291
381
  resolve(success);
292
382
  } else {
293
- error.head.msg = res;
294
- reject(error);
383
+ if (ossFailedApiOption) {
384
+ this._apiSubmit(resolve, reject, file);
385
+ } else {
386
+ error.head.msg = res;
387
+ reject(error);
388
+ }
295
389
  }
296
390
  },
297
391
  fail: (error) => {
298
- console.log(error);
299
- reject(error);
392
+ console.log('上传失败', ossFailedApiOption);
393
+ if (ossFailedApiOption) {
394
+ this._apiSubmit(resolve, reject, file);
395
+ } else {
396
+ console.log(error);
397
+ reject(error);
398
+ }
300
399
  }
301
400
  });
302
401
  } catch (e) {
package/dist/index.min.js CHANGED
@@ -1 +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;
1
+ "use strict";function e(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==n)return;var r,a,o=[],i=!0,s=!1;try{for(n=n.call(e);!(i=(r=n.next()).done)&&(o.push(r.value),!t||o.length!==t);i=!0);}catch(e){s=!0,a=e}finally{try{i||null==n.return||n.return()}finally{if(s)throw a}}return o}(e,t)||n(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function t(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=n(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var a=0,o=function(){};return{s:o,n:function(){return a>=e.length?{done:!0}:{done:!1,value:e[a++]}},e:function(e){throw e},f:o}}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 i,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,i=e},f:function(){try{s||null==r.return||r.return()}finally{if(u)throw i}}}}function n(e,t){if(e){if("string"==typeof e)return r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(e,t):void 0}}function r(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 a(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 o(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?a(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t,n,r,a,o,i){try{var s=e[o](i),u=s.value}catch(e){return void n(e)}s.done?t(u):Promise.resolve(u).then(r,a)}function u(e){return function(){var t=this,n=arguments;return new Promise((function(r,a){var o=e.apply(t,n);function i(e){s(o,r,a,i,u,"next",e)}function u(e){s(o,r,a,i,u,"throw",e)}i(void 0)}))}}function c(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 p=0;function l(e){return e&&e.size}var f,h={ALIYUN:"ALIYUN",TXYUN:"TXYUN",HUAWEI:"HUAWEI"},d=function(e){return f||(f=new m(e)),f},m=function(){function n(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,n),this._init(e)}var r,a,i,s,f,d,m,g,y,b,v;return r=n,a=[{key:"_init",value:(v=u(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 v.apply(this,arguments)})},{key:"initOptions",value:(b=u(regeneratorRuntime.mark((function e(t){var n,r,a,i,s,u,c,l;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=o(o({},this.params),t));case 3:if(n=this.params,r=n.type,a=n.getOptionFun,i=n.path,s=n.getAuthInfoFunc,u=n.isUploadWebp,c=n.ossFailedApiOption,this.getAuthInfoFunc=s,this.options={type:r,isUploadWebp:u,ossFailedApiOption:c},!a){e.next=16;break}return p=0,e.next=10,this._initOptionFun();case 10:if(l=e.sent){e.next=13;break}return e.abrupt("return");case 13:(i=i||l.path)&&!i.endsWith("/")&&(l.path=i+"/"),this.options=o(o({},this.options),l);case 16:case"end":return e.stop()}}),e,this)}))),function(e){return b.apply(this,arguments)})},{key:"_initOptionFun",value:(y=u(regeneratorRuntime.mark((function e(){var t=this;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",new Promise((function(e){var n=setInterval(u(regeneratorRuntime.mark((function r(){var a;return regeneratorRuntime.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return p>10&&(console.log("oss初始化失败"),clearInterval(n),p=0,e({})),console.log("初始化oss重试",p),p++,r.next=5,t.params.getOptionFun(t.params.type);case 5:null!=(a=r.sent)&&a.endPoint&&(clearInterval(n),e(a));case 7:case"end":return r.stop()}}),r)}))),1e3)})));case 1:case"end":return e.stop()}}),e)}))),function(){return y.apply(this,arguments)})},{key:"_isTimeOut",value:function(){var e=this.options.timeOut-1e4;return(new Date).getTime()>e}},{key:"upload",value:(g=u(regeneratorRuntime.mark((function e(t){var n,r,a,o,i,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 o=n[a],e.next=9,this.uploadFile(o);case 9:i=e.sent,s=i.data,u=i.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 g.apply(this,arguments)})},{key:"uploadFile",value:(m=u(regeneratorRuntime.mark((function e(t){var n,r,a,i,s,u=this,c=arguments;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=c.length>1&&void 0!==c[1]?c[1]:{},this.options&&null!==(n=this.options)&&void 0!==n&&n.endPoint&&!this._isTimeOut()){e.next=5;break}return console.log("初始化 oss 开始"),e.next=5,this.initOptions();case 5:return console.log("sadais uploader 上传文件",t),t=!l(t)&&l(t.path)?t.path:t,this.options=o(o({},this.options),r),!t.name&&t.path&&(a=t.path.startsWith("blob"),i=t.path.startsWith("data"),s=a||i?".png":t.path.substring(t.path.lastIndexOf(".")),t.name=this._guid()+s),e.abrupt("return",new Promise((function(e,n){u.options.endPoint?u.options.isUploadWebp&&h.TXYUN==u.params.type&&u._fileIsPic(t.name)?u._putSubmit(e,n,t):u._formSubmit(e,n,t):(console.log("oss 初始化失败,走接口上传"),u._apiSubmit(e,n,t))})));case 10:case"end":return e.stop()}}),e,this)}))),function(e){return m.apply(this,arguments)})},{key:"uploadFiles",value:(d=u(regeneratorRuntime.mark((function e(n){var r,a,o,i,s,u,c,p,l=arguments;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=l.length>1&&void 0!==l[1]?l[1]:{},a=[],o=[],i=t(n),e.prev=4,i.s();case 6:if((s=i.n()).done){e.next=16;break}return u=s.value,e.next=10,this.uploadFile(u,r);case 10:c=e.sent,p=c.data,0===c.head.ret?a.push(p):o.push(p);case 14:e.next=6;break;case 16:e.next=21;break;case 18:e.prev=18,e.t0=e.catch(4),i.e(e.t0);case 21:return e.prev=21,i.f(),e.finish(21);case 24:return e.abrupt("return",{successUrls:a,failUrls:o});case 25:case"end":return e.stop()}}),e,this,[[4,18,21,24]])}))),function(e){return d.apply(this,arguments)})},{key:"_formSubmit",value:function(e,t,n){console.log("表单上传");var r=this.options.domain,a=this._buildParams(n),o=a.url,i={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:o,filePath:n.path,name:"file",formData:a,timeout:this.options.uploadTimeOut||2e4,success:function(n){200==n.statusCode?e(i):(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.timeout=this.options.uploadTimeOut||2e4,c.open("POST",o,!0),c.onreadystatechange=function(){c.readyState===XMLHttpRequest.DONE&&(200===c.status?e(i):t(s))},c.send(u)}}},{key:"_apiSubmit",value:(f=u(regeneratorRuntime.mark((function t(n,r,a){var o,i,s,u,c,p,l,f,h,d,m,g,y,b;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return console.log("api接口上传"),o=this.options.ossFailedApiOption,i={data:"",head:{ret:0,msg:"success"}},s={data:a.name,head:{ret:1,msg:"fail"}},t.prev=4,t.next=7,uni.uploadFile({url:o.api,filePath:a.path,name:"file",timeout:this.options.uploadTimeOut||2e4});case 7:if(u=t.sent,c=e(u,2),p=c[1],console.log("api接口上传结果",p),f=(l=p||{}).errMsg,h=l.data,f&&"uploadFile:ok"===f){t.next=14;break}throw new Error(f);case 14:d=JSON.parse(h),m=d.data,g=d.head,y=(g=void 0===g?{}:g).ret,b=g.msg,y!==o.successRetCode?(s.head.msg=b,r(s)):(i.data=m.url,n(i)),t.next=23;break;case 20:t.prev=20,t.t0=t.catch(4),r(t.t0);case 23:case"end":return t.stop()}}),t,this,[[4,20]])}))),function(e,t,n){return f.apply(this,arguments)})},{key:"_putSubmit",value:(s=u(regeneratorRuntime.mark((function e(t,n,r){var a,o,i,s,u,c,p,l,f,h,d,m,g,y,b,v,x,k=this;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return console.log("腾讯put上传"),a=this.options,o=a.domain,i=a.ossFailedApiOption,s=this._buildParams(r),u=s.url+"/"+s.key,c=JSON.stringify({is_pic_info:1,rules:[{fileid:"/"+s.key,rule:"imageMogr2/format/webp"}]}),p={httpMethodName:"PUT",resoucePath:"/"+s.key,storage:this.params.type,headerMap:{"Pic-Operations":c}},l={},e.prev=7,console.log("获取权限信息"),e.next=11,this.getAuthInfoFunc(p);case 11:if(l=e.sent,console.log("获取权限结果",l),l.content){e.next=15;break}return e.abrupt("return",this._apiSubmit(t,n,r));case 15:e.next=21;break;case 17:return e.prev=17,e.t0=e.catch(7),console.log("获取权限失败",e.t0),e.abrupt("return",this._apiSubmit(t,n,r));case 21:if(f=l?l.content:""){e.next=24;break}return e.abrupt("return",n(m));case 24:h="".concat(o).concat(o.endsWith("/")?"":"/").concat(s.key),d={data:h,head:{ret:0,msg:"success"}},m={data:r.name,head:{ret:1,msg:"fail"}},g=function(e){console.log("上传数据",e);try{uni.request({url:u,method:"PUT",data:e,header:{Authorization:f,"Pic-Operations":c},timeout:k.options.uploadTimeOut||2e4,success:function(e){console.log("上传结果",e),200==e.statusCode?t(d):i?k._apiSubmit(t,n,r):(m.head.msg=e,n(m))},fail:function(e){console.log("上传失败",i),i?k._apiSubmit(t,n,r):(console.log(e),n(e))}})}catch(r){console.log("web环境");var a=new XMLHttpRequest;a.open("PUT",u,!0),a.setRequestHeader("Authorization",f),a.setRequestHeader("Pic-Operations",c),a.onreadystatechange=function(){a.readyState===XMLHttpRequest.DONE&&(200===a.status?t(d):n(m))},a.send(e)}},e.prev=28,console.log("微信环境"),y=uni.getFileSystemManager(),b=y.readFileSync(r.path),g(b),e.next=48;break;case 35:if(e.prev=35,e.t1=e.catch(28),console.log("H5环境"),!r.type){e.next=42;break}g(r),e.next=48;break;case 42:return e.next=44,fetch(r.path).then((function(e){return e.blob()}));case 44:v=e.sent,(x=new FileReader).onload=function(){g(x.result)},x.readAsArrayBuffer(v);case 48:case"end":return e.stop()}}),e,this,[[7,17],[28,35]])}))),function(e,t,n){return s.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 h.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")):h.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("."),o=e.substring(0,a),i=e.substring(a+1),s=n?"/".concat(o):"";return"".concat(r).concat(this._getNowDate(),"/").concat(this._guid()).concat(s,".").concat(i)}},{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&&c(r.prototype,a),i&&c(r,i),Object.defineProperty(r,"prototype",{writable:!1}),n}();exports.DEFAULT_OPTIONS={},exports.UPLOADER_TYPE=h,exports.UploaderInstance=d;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sadais/uploader",
3
- "version": "0.4.5",
3
+ "version": "0.4.7",
4
4
  "main": "dist/index.min.js",
5
5
  "module": "dist/index.es.js",
6
6
  "keywords": [