@sadais/uploader 0.3.6 → 0.3.8

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,11 +1,10 @@
1
1
  /*
2
2
  * @Author: fuwenlong
3
3
  * @Date: 2022-01-14 14:22:39
4
- * @LastEditTime: 2022-07-22 11:00:06
4
+ * @LastEditTime: 2024-02-22 14:51:02
5
5
  * @LastEditors: zhangzhenfei
6
6
  * @Description: 文件上传
7
7
  */
8
-
9
8
  // 对象存储类型
10
9
  const UPLOADER_TYPE = {
11
10
  ALIYUN: 'ALIYUN', // 阿里云
@@ -66,15 +65,17 @@ class SadaisUploader {
66
65
  ...customParams
67
66
  })
68
67
  }
69
- let { type, getOptionFun } = this.params;
70
-
68
+ let { type, getOptionFun, path, getAuthInfoFunc, isUploadWebp } = this.params;
69
+ this.getAuthInfoFunc = getAuthInfoFunc;
70
+ this.options = { type, isUploadWebp };
71
71
  if (getOptionFun) {
72
72
  const options = await getOptionFun(type);
73
73
  if (!options) return
74
- if (options.path && !options.path.endsWith('/')) {
75
- options.path = options.path + '/';
74
+ path = path || options.path;
75
+ if (path && !path.endsWith('/')) {
76
+ options.path = path + '/';
76
77
  }
77
- this.options = { ...options, type };
78
+ this.options = { ...this.options, ...options };
78
79
  }
79
80
  }
80
81
 
@@ -112,40 +113,166 @@ class SadaisUploader {
112
113
  * @param {File} file
113
114
  * @return Promise
114
115
  */
115
- async uploadFile(file) {
116
+ async uploadFile(file, opts = {}) {
116
117
  if (!this.options || this._isTimeOut()) {
117
118
  await this.initOptions();
118
119
  }
120
+ this.options = {
121
+ ...this.options,
122
+ ...opts
123
+ };
119
124
  if (!file.name && file.path) {
120
125
  const isBlobFile = file.path.startsWith('blob');
121
- const suffix = !isBlobFile ? file.path.substring(file.path.lastIndexOf('.')) : '.png';
126
+ const isBase64File = file.path.startsWith('data');
127
+ const suffix =
128
+ isBlobFile || isBase64File ? '.png' : file.path.substring(file.path.lastIndexOf('.'));
122
129
  file.name = this._guid() + suffix;
123
130
  }
124
131
  return new Promise((resolve, reject) => {
125
- const { domain } = this.options;
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
+ }
126
144
 
127
- // 请求地址
128
- const formData = this._buildParams(file);
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
+ }
129
163
 
130
- const apiUrl = formData.url;
131
- const uploadedFilePath = `${domain}${domain.endsWith('/') ? '' : '/'}${formData.key}`;
132
- const success = {
133
- data: uploadedFilePath,
134
- head: { ret: 0, msg: 'success' }
135
- };
136
- const error = {
137
- data: file.name,
138
- head: { ret: 1, msg: 'fail' }
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
+ }
139
222
  };
223
+ xhr.send(data);
224
+ }
225
+ }
226
+
227
+ // 腾讯put上传
228
+ async _putSubmit(resolve, reject, file) {
229
+ const { domain } = this.options;
140
230
 
141
- try {
142
- // uniapp
143
- uni.uploadFile({
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?.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
+ if (uni) {
267
+ uni.request({
144
268
  url: apiUrl,
145
- filePath: file.path, // uni api提供的blob格式图片地址
146
- name: 'file',
147
- formData,
148
- success: (res) => {
269
+ method: 'PUT',
270
+ data,
271
+ header: {
272
+ 'Authorization': authorizationInfo,
273
+ 'Pic-Operations': picOperations
274
+ },
275
+ success: res => {
149
276
  const { statusCode } = res;
150
277
  if (statusCode == 200) {
151
278
  resolve(success);
@@ -154,21 +281,17 @@ class SadaisUploader {
154
281
  reject(error);
155
282
  }
156
283
  },
157
- fail: (error) => {
284
+ fail: error => {
158
285
  console.log(error);
159
286
  reject(error);
160
287
  }
161
288
  });
162
- // H5 input:file接收内容
163
- } catch (e) {
164
- console.log('uni报错,调用XMLHttpRequest', e);
165
- const data = new FormData();
166
- Object.keys(formData).forEach((key) => {
167
- data.append(key, formData[key]);
168
- });
169
- data.append('file', file);
289
+ } else {
290
+ console.log('web环境');
170
291
  const xhr = new XMLHttpRequest();
171
- xhr.open('POST', apiUrl, true);
292
+ xhr.open('PUT', apiUrl, true);
293
+ xhr.setRequestHeader('Authorization', authorizationInfo);
294
+ xhr.setRequestHeader('Pic-Operations', picOperations);
172
295
  xhr.onreadystatechange = () => {
173
296
  if (xhr.readyState === XMLHttpRequest.DONE) {
174
297
  if (xhr.status === 200) {
@@ -180,26 +303,23 @@ class SadaisUploader {
180
303
  };
181
304
  xhr.send(data);
182
305
  }
183
- })
306
+ };
307
+ if (uni && uni.getFileSystemManager()) {
308
+ console.log('微信环境');
309
+ const fileManager = uni.getFileSystemManager();
310
+ const fileData = fileManager.readFileSync(file.path);
311
+ uploadFunc(fileData);
312
+ } else if (fetch) {
313
+ console.log('H5环境');
314
+ const fileObj = await fetch(file.path).then(r => r.blob());
315
+ uploadFunc(fileObj);
316
+ }
184
317
  }
185
318
 
186
- /**
187
- * 多文件上传
188
- * @param {Array<File>} files
189
- * @return Promise
190
- */
191
- async uploadFiles(files) {
192
- const successUrls = [];
193
- const failUrls = [];
194
- for (const file of files) {
195
- const { data, head } = await this.uploadFile(file);
196
- if (head.ret === 0) {
197
- successUrls.push(data);
198
- } else {
199
- failUrls.push(data);
200
- }
201
- }
202
- return { successUrls, failUrls }
319
+ _fileIsPic(name) {
320
+ const suffix = name.substring(name.lastIndexOf('.') + 1);
321
+ const suffixs = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'avif', 'heif', 'tpg', 'psd'];
322
+ return suffixs.includes(suffix.toLowerCase())
203
323
  }
204
324
 
205
325
  // 按类型组装过参数
@@ -218,7 +338,6 @@ class SadaisUploader {
218
338
  params['q-signature'] = opt.signature; // 签名
219
339
  params['q-sign-algorithm'] = 'sha1'; // 签名算法
220
340
  params['q-key-time'] = opt.param['q-sign-time'];
221
- // params['q-sign-time'] = opt.param['q-sign-time']
222
341
  params.url = `https://${opt.bucketName}.cos.${endPoint}.myqcloud.com`;
223
342
  } else if (UPLOADER_TYPE.HUAWEI === type) {
224
343
  params.AccessKeyId = opt.accessKeyId;
@@ -240,10 +359,15 @@ class SadaisUploader {
240
359
  * @returns
241
360
  */
242
361
  _getUploadFilePath(name) {
362
+ const type = this.params.type;
243
363
  const { useOriginalName, path } = this.options;
244
364
  const lastIndexOf = name.lastIndexOf('.');
245
365
  const originalName = name.substring(0, lastIndexOf);
246
- const suffix = name.substring(lastIndexOf + 1);
366
+ let suffix = name.substring(lastIndexOf + 1);
367
+ // 腾讯云上传图片固定为webp格式
368
+ if (UPLOADER_TYPE.TXYUN == type && this._fileIsPic(name)) {
369
+ suffix = 'webp';
370
+ }
247
371
  const fileName = useOriginalName ? `/${originalName}` : '';
248
372
  // 为了保证使用文件原名时,文件不被覆盖,仍然使用随机生成方式
249
373
  // ${this._getNowDate()}/
package/dist/index.min.js CHANGED
@@ -1 +1 @@
1
- "use strict";function e(e,r){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,r){if(!e)return;if("string"==typeof e)return t(e,r);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return t(e,r)}(e))||r&&e&&"number"==typeof e.length){n&&(e=n);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,u=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return u=e.done,e},e:function(e){c=!0,o=e},f:function(){try{u||null==n.return||n.return()}finally{if(c)throw o}}}}function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function r(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function n(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){a(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function i(e,t,r,n,a,i,o){try{var u=e[i](o),c=u.value}catch(e){return void r(e)}u.done?t(c):Promise.resolve(c).then(n,a)}function o(e){return function(){var t=this,r=arguments;return new Promise((function(n,a){var o=e.apply(t,r);function u(e){i(o,n,a,u,c,"next",e)}function c(e){i(o,n,a,u,c,"throw",e)}u(void 0)}))}}function u(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}Object.defineProperty(exports,"__esModule",{value:!0});var c,s={ALIYUN:"ALIYUN",TXYUN:"TXYUN",HUAWEI:"HUAWEI"},p=function(e){return c||(c=new l(e)),c},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 r,a,i,c,p,l,f,h;return r=t,a=[{key:"_init",value:(h=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 h.apply(this,arguments)})},{key:"initOptions",value:(f=o(regeneratorRuntime.mark((function e(t){var r,a,i,o;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=n(n({},this.params),t));case 3:if(r=this.params,a=r.type,!(i=r.getOptionFun)){e.next=12;break}return e.next=7,i(a);case 7:if(o=e.sent){e.next=10;break}return e.abrupt("return");case 10:o.path&&!o.path.endsWith("/")&&(o.path=o.path+"/"),this.options=n(n({},o),{},{type:a});case 12:case"end":return e.stop()}}),e,this)}))),function(e){return f.apply(this,arguments)})},{key:"_isTimeOut",value:function(){var e=this.options.timeOut-1e4;return(new Date).getTime()>e}},{key:"upload",value:(l=o(regeneratorRuntime.mark((function e(t){var r,n,a,i,o,u,c;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:r=Array.isArray(t)?t:[t],n=[],a=0;case 5:if(!(a<r.length)){e.next=16;break}return i=r[a],e.next=9,this.uploadFile(i);case 9:o=e.sent,u=o.data,c=o.head,n.push({index:a,url:u,ret:c.ret});case 13:a++,e.next=5;break;case 16:return e.abrupt("return",n);case 17:case"end":return e.stop()}}),e,this)}))),function(e){return l.apply(this,arguments)})},{key:"uploadFile",value:(p=o(regeneratorRuntime.mark((function e(t){var r,n,a=this;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.options&&!this._isTimeOut()){e.next=3;break}return e.next=3,this.initOptions();case 3:return!t.name&&t.path&&(r=t.path.startsWith("blob"),n=r?".png":t.path.substring(t.path.lastIndexOf(".")),t.name=this._guid()+n),e.abrupt("return",new Promise((function(e,r){var n=a.options.domain,i=a._buildParams(t),o=i.url,u={data:"".concat(n).concat(n.endsWith("/")?"":"/").concat(i.key),head:{ret:0,msg:"success"}},c={data:t.name,head:{ret:1,msg:"fail"}};try{uni.uploadFile({url:o,filePath:t.path,name:"file",formData:i,success:function(t){200==t.statusCode?e(u):(c.head.msg=t,r(c))},fail:function(e){console.log(e),r(e)}})}catch(n){console.log("uni报错,调用XMLHttpRequest",n);var s=new FormData;Object.keys(i).forEach((function(e){s.append(e,i[e])})),s.append("file",t);var p=new XMLHttpRequest;p.open("POST",o,!0),p.onreadystatechange=function(){p.readyState===XMLHttpRequest.DONE&&(200===p.status?e(u):r(c))},p.send(s)}})));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return p.apply(this,arguments)})},{key:"uploadFiles",value:(c=o(regeneratorRuntime.mark((function t(r){var n,a,i,o,u,c,s;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:n=[],a=[],i=e(r),t.prev=3,i.s();case 5:if((o=i.n()).done){t.next=15;break}return u=o.value,t.next=9,this.uploadFile(u);case 9:c=t.sent,s=c.data,0===c.head.ret?n.push(s):a.push(s);case 13:t.next=5;break;case 15:t.next=20;break;case 17:t.prev=17,t.t0=t.catch(3),i.e(t.t0);case 20:return t.prev=20,i.f(),t.finish(20);case 23:return t.abrupt("return",{successUrls:n,failUrls:a});case 24:case"end":return t.stop()}}),t,this,[[3,17,20,23]])}))),function(e){return c.apply(this,arguments)})},{key:"_buildParams",value:function(e){var t=this.options,r=t.type,n={name:e.name,policy:t.policy,success_action_status:"200",key:this._getUploadFilePath(e.name)},a=t.endPoint.replace("https://","").replace("http://","");return s.TXYUN===r?(n["q-ak"]=t.accessKeyId,n["q-signature"]=t.signature,n["q-sign-algorithm"]="sha1",n["q-key-time"]=t.param["q-sign-time"],n.url="https://".concat(t.bucketName,".cos.").concat(a,".myqcloud.com")):s.HUAWEI===r?(n.AccessKeyId=t.accessKeyId,n.signature=t.signature,n.url="https://".concat(t.bucketName,".obs.").concat(a,".myhuaweicloud.com")):(n.signature=t.signature,n.OSSAccessKeyId=t.accessKeyId,n.bucket=t.bucketName,n.url="https://".concat(t.bucketName,".").concat(a)),n}},{key:"_getUploadFilePath",value:function(e){var t=this.options,r=t.useOriginalName,n=t.path,a=e.lastIndexOf("."),i=e.substring(0,a),o=e.substring(a+1),u=r?"/".concat(i):"";return"".concat(n).concat(this._getNowDate(),"/").concat(this._guid()).concat(u,".").concat(o)}},{key:"_getNowDate",value:function(){var e=new Date,t=e.getFullYear(),r=e.getMonth()+1,n=e.getDate();return r<10&&(r="0".concat(r)),n<10&&(n="0".concat(n)),"".concat(t).concat(r).concat(n)}},{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&&u(r.prototype,a),i&&u(r,i),Object.defineProperty(r,"prototype",{writable:!1}),t}();exports.DEFAULT_OPTIONS={},exports.UPLOADER_TYPE=s,exports.UploaderInstance=p;
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,g,y;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=null==c?void 0:c.content){e.next=11;break}return e.abrupt("return",n(h));case 11:if(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){if(uni)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)}});else{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)}},!uni||!uni.getFileSystemManager()){e.next=22;break}console.log("微信环境"),m=uni.getFileSystemManager(),g=m.readFileSync(r.path),d(g),e.next=28;break;case 22:if(!fetch){e.next=28;break}return console.log("H5环境"),e.next=26,fetch(r.path).then((function(e){return e.blob()}));case 26:y=e.sent,d(y);case 28:case"end":return e.stop()}}),e,this)}))),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){var t=this.params.type,n=this.options,r=n.useOriginalName,a=n.path,i=e.lastIndexOf("."),o=e.substring(0,i),s=e.substring(i+1);c.TXYUN==t&&this._fileIsPic(e)&&(s="webp");var u=r?"/".concat(o):"";return"".concat(a).concat(this._getNowDate(),"/").concat(this._guid()).concat(u,".").concat(s)}},{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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sadais/uploader",
3
- "version": "0.3.6",
3
+ "version": "0.3.8",
4
4
  "main": "dist/index.min.js",
5
5
  "module": "dist/index.es.js",
6
6
  "keywords": [