@sadais/uploader 0.4.6 → 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-07-04 12:28:48
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
  }
@@ -74,7 +78,8 @@ class SadaisUploader {
74
78
  this.getAuthInfoFunc = getAuthInfoFunc;
75
79
  this.options = { type, isUploadWebp, ossFailedApiOption };
76
80
  if (getOptionFun) {
77
- const options = await getOptionFun(type);
81
+ initOssRetry = 0;
82
+ const options = await this._initOptionFun();
78
83
  if (!options) return
79
84
  path = path || options.path;
80
85
  if (path && !path.endsWith('/')) {
@@ -84,6 +89,26 @@ class SadaisUploader {
84
89
  }
85
90
  }
86
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
+
87
112
  /**
88
113
  * 是否超时
89
114
  */
@@ -119,7 +144,8 @@ class SadaisUploader {
119
144
  * @return Promise
120
145
  */
121
146
  async uploadFile(file, opts = {}) {
122
- if (!this.options || this._isTimeOut()) {
147
+ if (!this.options || !this.options?.endPoint || this._isTimeOut()) {
148
+ console.log('初始化 oss 开始');
123
149
  await this.initOptions();
124
150
  }
125
151
 
@@ -143,7 +169,11 @@ class SadaisUploader {
143
169
  }
144
170
 
145
171
  return new Promise((resolve, reject) => {
146
- if (
172
+ if (!this.options.endPoint) {
173
+ // oss 初始化失败的情况下,走接口上传
174
+ console.log('oss 初始化失败,走接口上传');
175
+ this._apiSubmit(resolve, reject, file);
176
+ } else if (
147
177
  this.options.isUploadWebp &&
148
178
  UPLOADER_TYPE.TXYUN == this.params.type &&
149
179
  this._fileIsPic(file.name)
@@ -253,29 +283,36 @@ class SadaisUploader {
253
283
  head: { ret: 1, msg: 'fail' }
254
284
  };
255
285
 
256
- const [, result] = await uni.uploadFile({
257
- url: ossFailedApiOption.api,
258
- filePath: file.path,
259
- name: 'file'
260
- });
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);
261
294
 
262
- const { errMsg, data: resData } = result || {};
263
- if (!errMsg || errMsg !== 'uploadFile:ok') {
264
- throw new Error(errMsg)
265
- }
266
- const { data, head: { ret, msg } = {} } = JSON.parse(resData);
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);
267
300
 
268
- if (ret !== ossFailedApiOption.successRetCode) {
269
- error.head.msg = msg;
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) {
270
309
  reject(error);
271
- } else {
272
- success.data = data.url;
273
- resolve(success);
274
310
  }
275
311
  }
276
312
 
277
313
  // 腾讯put上传
278
314
  async _putSubmit(resolve, reject, file) {
315
+ console.log('腾讯put上传');
279
316
  const { domain, ossFailedApiOption } = this.options;
280
317
 
281
318
  const formData = this._buildParams(file);
@@ -299,7 +336,20 @@ class SadaisUploader {
299
336
  'Pic-Operations': picOperations
300
337
  }
301
338
  };
302
- 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
+
303
353
  const authorizationInfo = authInfo ? authInfo.content : '';
304
354
  if (!authorizationInfo) return reject(error)
305
355
  const uploadedFilePath = `${domain}${domain.endsWith('/') ? '' : '/'}${formData.key}`;
@@ -313,6 +363,7 @@ class SadaisUploader {
313
363
  };
314
364
 
315
365
  const uploadFunc = (data) => {
366
+ console.log('上传数据', data);
316
367
  try {
317
368
  uni.request({
318
369
  url: apiUrl,
@@ -322,7 +373,9 @@ class SadaisUploader {
322
373
  'Authorization': authorizationInfo,
323
374
  'Pic-Operations': picOperations
324
375
  },
376
+ timeout: this.options.uploadTimeOut || 20000, // 默认20s
325
377
  success: (res) => {
378
+ console.log('上传结果', res);
326
379
  const { statusCode } = res;
327
380
  if (statusCode == 200) {
328
381
  resolve(success);
@@ -336,6 +389,7 @@ class SadaisUploader {
336
389
  }
337
390
  },
338
391
  fail: (error) => {
392
+ console.log('上传失败', ossFailedApiOption);
339
393
  if (ossFailedApiOption) {
340
394
  this._apiSubmit(resolve, reject, file);
341
395
  } else {
package/dist/index.min.js CHANGED
@@ -1 +1 @@
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,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}(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,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 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 i(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){o(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 o(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,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 u(e){return function(){var t=this,n=arguments;return new Promise((function(r,a){var i=e.apply(t,n);function o(e){s(i,r,a,o,u,"next",e)}function u(e){s(i,r,a,o,u,"throw",e)}o(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)}}function p(e){return e&&e.size}Object.defineProperty(exports,"__esModule",{value:!0});var l,f={ALIYUN:"ALIYUN",TXYUN:"TXYUN",HUAWEI:"HUAWEI"},h=function(e){return l||(l=new d(e)),l},d=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,o,s,l,h,d,m,y,g;return r=n,a=[{key:"_init",value:(g=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 g.apply(this,arguments)})},{key:"initOptions",value:(y=u(regeneratorRuntime.mark((function e(t){var n,r,a,o,s,u,c,p;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=i(i({},this.params),t));case 3:if(n=this.params,r=n.type,a=n.getOptionFun,o=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=15;break}return e.next=9,a(r);case 9:if(p=e.sent){e.next=12;break}return e.abrupt("return");case 12:(o=o||p.path)&&!o.endsWith("/")&&(p.path=o+"/"),this.options=i(i({},this.options),p);case 15:case"end":return e.stop()}}),e,this)}))),function(e){return y.apply(this,arguments)})},{key:"_isTimeOut",value:function(){var e=this.options.timeOut-1e4;return(new Date).getTime()>e}},{key:"upload",value:(m=u(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 m.apply(this,arguments)})},{key:"uploadFile",value:(d=u(regeneratorRuntime.mark((function e(t){var n,r,a,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 console.log("sadais uploader 上传文件",t),t=!p(t)&&p(t.path)?t.path:t,this.options=i(i({},this.options),n),!t.name&&t.path&&(r=t.path.startsWith("blob"),a=t.path.startsWith("data"),o=r||a?".png":t.path.substring(t.path.lastIndexOf(".")),t.name=this._guid()+o),e.abrupt("return",new Promise((function(e,n){s.options.isUploadWebp&&f.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 d.apply(this,arguments)})},{key:"uploadFiles",value:(h=u(regeneratorRuntime.mark((function e(n){var r,a,i,o,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=[],i=[],o=t(n),e.prev=4,o.s();case 6:if((s=o.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):i.push(p);case 14:e.next=6;break;case 16:e.next=21;break;case 18:e.prev=18,e.t0=e.catch(4),o.e(e.t0);case 21:return e.prev=21,o.f(),e.finish(21);case 24:return e.abrupt("return",{successUrls:a,failUrls:i});case 25:case"end":return e.stop()}}),e,this,[[4,18,21,24]])}))),function(e){return h.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,timeout:this.options.uploadTimeOut||2e4,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.timeout=this.options.uploadTimeOut||2e4,c.open("POST",i,!0),c.onreadystatechange=function(){c.readyState===XMLHttpRequest.DONE&&(200===c.status?e(o):t(s))},c.send(u)}}},{key:"_apiSubmit",value:(l=u(regeneratorRuntime.mark((function t(n,r,a){var i,o,s,u,c,p,l,f,h,d,m,y,g,b;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return console.log("api接口上传"),i=this.options.ossFailedApiOption,o={data:"",head:{ret:0,msg:"success"}},s={data:a.name,head:{ret:1,msg:"fail"}},t.next=6,uni.uploadFile({url:i.api,filePath:a.path,name:"file"});case 6:if(u=t.sent,c=e(u,2),p=c[1],f=(l=p||{}).errMsg,h=l.data,f&&"uploadFile:ok"===f){t.next=12;break}throw new Error(f);case 12:d=JSON.parse(h),m=d.data,y=d.head,g=(y=void 0===y?{}:y).ret,b=y.msg,g!==i.successRetCode?(s.head.msg=b,r(s)):(o.data=m.url,n(o));case 16:case"end":return t.stop()}}),t,this)}))),function(e,t,n){return l.apply(this,arguments)})},{key:"_putSubmit",value:(s=u(regeneratorRuntime.mark((function e(t,n,r){var a,i,o,s,u,c,p,l,f,h,d,m,y,g,b,v,x,k=this;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=this.options,i=a.domain,o=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}},e.next=7,this.getAuthInfoFunc(p);case 7:if(l=e.sent,f=l?l.content:""){e.next=11;break}return e.abrupt("return",n(m));case 11:h="".concat(i).concat(i.endsWith("/")?"":"/").concat(s.key),d={data:h,head:{ret:0,msg:"success"}},m={data:r.name,head:{ret:1,msg:"fail"}},y=function(e){try{uni.request({url:u,method:"PUT",data:e,header:{Authorization:f,"Pic-Operations":c},success:function(e){200==e.statusCode?t(d):o?k._apiSubmit(t,n,r):(m.head.msg=e,n(m))},fail:function(e){o?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=15,console.log("微信环境"),g=uni.getFileSystemManager(),b=g.readFileSync(r.path),y(b),e.next=35;break;case 22:if(e.prev=22,e.t0=e.catch(15),console.log("H5环境"),!r.type){e.next=29;break}y(r),e.next=35;break;case 29:return e.next=31,fetch(r.path).then((function(e){return e.blob()}));case 31:v=e.sent,(x=new FileReader).onload=function(){y(x.result)},x.readAsArrayBuffer(v);case 35:case"end":return e.stop()}}),e,this,[[15,22]])}))),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 f.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")):f.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&&c(r.prototype,a),o&&c(r,o),Object.defineProperty(r,"prototype",{writable:!1}),n}();exports.DEFAULT_OPTIONS={},exports.UPLOADER_TYPE=f,exports.UploaderInstance=h;
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.6",
3
+ "version": "0.4.7",
4
4
  "main": "dist/index.min.js",
5
5
  "module": "dist/index.es.js",
6
6
  "keywords": [