@sadais/uploader 0.3.3 → 0.3.6

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/README.md CHANGED
@@ -1,80 +1,80 @@
1
- ## 开始
2
-
3
- ```bash
4
- # 安装依赖
5
- npx yarn
6
- # 监听实时构建`/dist`
7
- npm run dev
8
- # 只构建`/dist`一次,不作监听
9
- npm run build
10
- ```
11
-
12
- ### 发布包到私服
13
-
14
- ```bash
15
- # 登录npm服务器
16
- npm login --registry https://registry.npmjs.org
17
- # 发布
18
- npm publish
19
- ```
20
-
21
- ## 发布之前测试
22
-
23
- 在当前工程,没有创建组件的单元测试,只能通过把构建后的东西复制到某个项目的 node_modules
24
-
25
- 比如当前 package.json 的包名是 "@sadais/uploader" , 发布前要在 A 项目中测试 "@sadais/uploader", 在 A 项目的 node_modules 新建 @sadais/uploader , 再把 /dist/ 和 package.json 拷贝到 A 项目的 node_modules/@sadais/uploader
26
-
27
- 使用
28
-
29
- ```js
30
-
31
- import { UploaderInstance,UPLOADER_TYPE } from '@sadais/uploader';
32
- const uploader = new UploaderInstance(
33
- {type:UPLOADER_TYPE.ALIYUN,getOptionFun:async (type) => {
34
- // 获取option示例
35
- const { head, data } = await apiGetUploadOption(type)
36
- if (head.ret !== this.$consts.RET_CODE.SUCCESS) return null
37
- return data
38
- }}
39
- )
40
-
41
- // 获取上传options示例
42
- export const apiGetUploadOption = async type => {
43
- const params = {
44
- storageenum: type
45
- }
46
- const { data } = await request.get('/api/manage/v1/storage/getstoragesignature', params)
47
- return data
48
- }
49
-
50
- // 调用说明
51
- //单文件上传
52
- const {data,head:{msg,ret}} = await uploader.uploadFile(file)
53
- // 0-成功 1-失败
54
- if(ret===this.$consts.RET_CODE.SUCCESS){
55
- const url = data
56
- }
57
- //多文件上传
58
- const {successUrls,failUrls} = await uploader.uploadFiles(files)
59
- // successUrls-上传成功的url数组
60
- // failUrls-上传失败的fileName数组
61
-
62
- //通用上传,支持单文件和多文件
63
- const [{index,url,ret}] = await uploader.upload(file|files)
64
- // 返回数组
65
- // index:上传文件的下标;
66
- // ret:状态,0-成功,1-失败;
67
- // url:上传成功的路径 或 上传失败的文件名
68
- ```
69
-
70
- ## 发布完成后
71
-
72
- 在 A 项目安装
73
-
74
- ```bash
75
- # use yarn
76
- npx yarn add @sadais/uploader -S
77
-
78
- # use npm or pnpm
79
- npx pnpm install @sadais/uploader -S
80
- ```
1
+ ## 开始
2
+
3
+ ```bash
4
+ # 安装依赖
5
+ npx yarn
6
+ # 监听实时构建`/dist`
7
+ npm run dev
8
+ # 只构建`/dist`一次,不作监听
9
+ npm run build
10
+ ```
11
+
12
+ ### 发布包到私服
13
+
14
+ ```bash
15
+ # 登录npm服务器
16
+ npm login --registry https://registry.npmjs.org
17
+ # 发布
18
+ npm publish
19
+ ```
20
+
21
+ ## 发布之前测试
22
+
23
+ 在当前工程,没有创建组件的单元测试,只能通过把构建后的东西复制到某个项目的 node_modules
24
+
25
+ 比如当前 package.json 的包名是 "@sadais/uploader" , 发布前要在 A 项目中测试 "@sadais/uploader", 在 A 项目的 node_modules 新建 @sadais/uploader , 再把 /dist/ 和 package.json 拷贝到 A 项目的 node_modules/@sadais/uploader
26
+
27
+ 使用
28
+
29
+ ```js
30
+
31
+ import { UploaderInstance,UPLOADER_TYPE } from '@sadais/uploader';
32
+ const uploader = new UploaderInstance(
33
+ {type:UPLOADER_TYPE.ALIYUN,getOptionFun:async (type) => {
34
+ // 获取option示例
35
+ const { head, data } = await apiGetUploadOption(type)
36
+ if (head.ret !== this.$consts.RET_CODE.SUCCESS) return null
37
+ return data
38
+ }}
39
+ )
40
+
41
+ // 获取上传options示例
42
+ export const apiGetUploadOption = async type => {
43
+ const params = {
44
+ storageenum: type
45
+ }
46
+ const { data } = await request.get('/api/manage/v1/storage/getstoragesignature', params)
47
+ return data
48
+ }
49
+
50
+ // 调用说明
51
+ //单文件上传
52
+ const {data,head:{msg,ret}} = await uploader.uploadFile(file)
53
+ // 0-成功 1-失败
54
+ if(ret===this.$consts.RET_CODE.SUCCESS){
55
+ const url = data
56
+ }
57
+ //多文件上传
58
+ const {successUrls,failUrls} = await uploader.uploadFiles(files)
59
+ // successUrls-上传成功的url数组
60
+ // failUrls-上传失败的fileName数组
61
+
62
+ //通用上传,支持单文件和多文件
63
+ const [{index,url,ret}] = await uploader.upload(file|files)
64
+ // 返回数组
65
+ // index:上传文件的下标;
66
+ // ret:状态,0-成功,1-失败;
67
+ // url:上传成功的路径 或 上传失败的文件名
68
+ ```
69
+
70
+ ## 发布完成后
71
+
72
+ 在 A 项目安装
73
+
74
+ ```bash
75
+ # use yarn
76
+ npx yarn add @sadais/uploader -S
77
+
78
+ # use npm or pnpm
79
+ npx pnpm install @sadais/uploader -S
80
+ ```
package/dist/index.es.js CHANGED
@@ -1,280 +1,285 @@
1
- /*
2
- * @Author: fuwenlong
3
- * @Date: 2022-01-14 14:22:39
4
- * @LastEditTime: 2022-05-25 10:20:33
5
- * @LastEditors: zhangzhenfei
6
- * @Description: 文件上传
7
- */
8
-
9
- // 对象存储类型
10
- const UPLOADER_TYPE = {
11
- ALIYUN: 'ALIYUN', // 阿里云
12
- TXYUN: 'TXYUN', // 腾讯云
13
- HUAWEI: 'HUAWEI' // 华为云
14
- };
15
-
16
- const DEFAULT_OPTIONS = {
17
- // type: UPLOADER_TYPE.ALIYUN, //
18
- // accessKeyId: 'LTAIXeOzClQBtKs3',
19
- // bucketName: 'sadais-oss',
20
- // endPoint: 'https://oss-cn-hangzhou.aliyuncs.com',
21
- // path: 'file',
22
- // signature: '6Y5l5k56y9VgxDU1vhsyCLC99QM=',
23
- // domain: 'https://m.antibao.cn',
24
- // policy:'',
25
- // timeOut: 1642476191415
26
- };
27
-
28
- /**
29
- * @param {String} params.type
30
- * @param {String} params.getOptionFun
31
- */
32
- const UploaderInstance = (function () {
33
- let instance;
34
- return function (params) {
35
- if (!instance) {
36
- instance = new SadaisUploader(params);
37
- }
38
- return instance
39
- }
40
- })();
41
-
42
- class SadaisUploader {
43
- constructor(params) {
44
- this._init(params);
45
- }
46
-
47
- /**
48
- * 初始化
49
- * @param {Object} options
50
- */
51
- async _init(params) {
52
- this.params = params;
53
- // 不在初始化的时候调用接口,上传文件时再调用,故注释以下代码
54
- // this._initOptions()
55
- }
56
-
57
- /**
58
- * 获取配置信息
59
- */
60
- async initOptions(customParams) {
61
- if (customParams) {
62
- this.params.type = customParams.type || this.params.type;
63
- this.params.getOptionFun = customParams.getOptionFun || this.params.getOptionFun;
64
- }
65
- let { type, getOptionFun } = this.params;
66
-
67
- if (getOptionFun) {
68
- const options = await getOptionFun(type);
69
- if (!options) return
70
- if (options.path && !options.path.endsWith('/')) {
71
- options.path = options.path + '/';
72
- }
73
- this.options = { ...options, type };
74
- }
75
- }
76
-
77
- /**
78
- * 是否超时
79
- */
80
- _isTimeOut() {
81
- // 比服务器timeOut时间提前10s过期
82
- const timeout = this.options.timeOut - 1000 * 10;
83
- return new Date().getTime() > timeout
84
- }
85
-
86
- /**
87
- * 文件上传
88
- * @param { File | Array<file> } file 文件或文件数组
89
- */
90
- async upload(file) {
91
- if (!file) return
92
- let files = Array.isArray(file) ? file : [file];
93
- const result = [];
94
- for (let i = 0; i < files.length; i++) {
95
- const item = files[i];
96
- const { data, head } = await this.uploadFile(item);
97
- result.push({
98
- index: i,
99
- url: data,
100
- ret: head.ret
101
- });
102
- }
103
- return result
104
- }
105
-
106
- /**
107
- * 单文件上传
108
- * @param {File} file
109
- * @return Promise
110
- */
111
- async uploadFile(file) {
112
- if (!this.options || this._isTimeOut()) {
113
- await this.initOptions();
114
- }
115
- if (!file.name && file.path) {
116
- const suffix = file.path.substring(file.path.lastIndexOf('.'));
117
- file.name = this._guid() + suffix;
118
- }
119
- return new Promise((resolve, reject) => {
120
- const { domain } = this.options;
121
-
122
- // 请求地址
123
- const formData = this._buildParams(file);
124
-
125
- const apiUrl = formData.url;
126
- const uploadedFilePath = `${domain}${domain.endsWith('/') ? '' : '/'}${formData.key}`;
127
- const success = {
128
- data: uploadedFilePath,
129
- head: { ret: 0, msg: 'success' }
130
- };
131
- const error = {
132
- data: file.name,
133
- head: { ret: 1, msg: 'fail' }
134
- };
135
-
136
- try {
137
- // uniapp
138
- uni.uploadFile({
139
- url: apiUrl,
140
- filePath: file.path, // uni api提供的blob格式图片地址
141
- name: 'file',
142
- formData,
143
- success: (res) => {
144
- const { statusCode } = res;
145
- if (statusCode == 200) {
146
- resolve(success);
147
- } else {
148
- error.head.msg = res;
149
- reject(error);
150
- }
151
- },
152
- fail: (error) => {
153
- console.log(error);
154
- reject(error);
155
- }
156
- });
157
- // H5 input:file接收内容
158
- } catch (e) {
159
- console.log('uni报错,调用XMLHttpRequest', e);
160
- const data = new FormData();
161
- Object.keys(formData).forEach((key) => {
162
- data.append(key, formData[key]);
163
- });
164
- data.append('file', file);
165
- const xhr = new XMLHttpRequest();
166
- xhr.open('POST', apiUrl, true);
167
- xhr.onreadystatechange = () => {
168
- if (xhr.readyState === XMLHttpRequest.DONE) {
169
- if (xhr.status === 200) {
170
- resolve(success);
171
- } else {
172
- reject(error);
173
- }
174
- }
175
- };
176
- xhr.send(data);
177
- }
178
- })
179
- }
180
-
181
- /**
182
- * 多文件上传
183
- * @param {Array<File>} files
184
- * @return Promise
185
- */
186
- async uploadFiles(files) {
187
- const successUrls = [];
188
- const failUrls = [];
189
- for (const file of files) {
190
- const { data, head } = await this.uploadFile(file);
191
- if (head.ret === 0) {
192
- successUrls.push(data);
193
- } else {
194
- failUrls.push(data);
195
- }
196
- }
197
- return { successUrls, failUrls }
198
- }
199
-
200
- // 按类型组装过参数
201
- _buildParams(file) {
202
- const opt = this.options;
203
- const type = opt.type;
204
- const params = {
205
- name: file.name,
206
- policy: opt.policy,
207
- success_action_status: '200',
208
- key: this._getUploadFilePath(file.name)
209
- };
210
- const endPoint = opt.endPoint.replace('https://', '').replace('http://', '');
211
- if (UPLOADER_TYPE.TXYUN === type) {
212
- params['q-ak'] = opt.accessKeyId;
213
- params['q-signature'] = opt.signature; // 签名
214
- params['q-sign-algorithm'] = 'sha1'; // 签名算法
215
- params['q-key-time'] = opt.param['q-sign-time'];
216
- // params['q-sign-time'] = opt.param['q-sign-time']
217
- params.url = `https://${opt.bucketName}.cos.${endPoint}.myqcloud.com`;
218
- } else if (UPLOADER_TYPE.HUAWEI === type) {
219
- params.AccessKeyId = opt.accessKeyId;
220
- params.signature = opt.signature;
221
- params.url = `https://${opt.bucketName}.obs.${endPoint}.myhuaweicloud.com`;
222
- } else {
223
- params.signature = opt.signature;
224
- params.OSSAccessKeyId = opt.accessKeyId;
225
- params.bucket = opt.bucketName;
226
-
227
- params.url = `https://${opt.bucketName}.${endPoint}`;
228
- }
229
- return params
230
- }
231
-
232
- /**
233
- * 获取上传文件路径
234
- * @param {String} name 文件名
235
- * @returns
236
- */
237
- _getUploadFilePath(name) {
238
- const { useOriginalName, path } = this.options;
239
- const lastIndexOf = name.lastIndexOf('.');
240
- const originalName = name.substring(0, lastIndexOf);
241
- const suffix = name.substring(lastIndexOf + 1);
242
- const fileName = useOriginalName ? `/${originalName}` : '';
243
- // 为了保证使用文件原名时,文件不被覆盖,仍然使用随机生成方式
244
- // ${this._getNowDate()}/
245
- return `${path}${this._getNowDate()}/${this._guid()}${fileName}.${suffix}`
246
- }
247
-
248
- /**
249
- * 获取当前日期
250
- * @returns YYYY-MM-DD
251
- */
252
- _getNowDate() {
253
- const date = new Date();
254
- const year = date.getFullYear();
255
- let month = date.getMonth() + 1;
256
- let day = date.getDate();
257
- if (month < 10) {
258
- month = `0${month}`;
259
- }
260
- if (day < 10) {
261
- day = `0${day}`;
262
- }
263
-
264
- return `${year}-${month}-${day}`
265
- }
266
-
267
- /**
268
- * 生成guid,用于生成随机文件名
269
- * @return String
270
- */
271
- _guid() {
272
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
273
- var r = (Math.random() * 16) | 0,
274
- v = c == 'x' ? r : (r & 0x3) | 0x8;
275
- return v.toString(16)
276
- })
277
- }
1
+ /*
2
+ * @Author: fuwenlong
3
+ * @Date: 2022-01-14 14:22:39
4
+ * @LastEditTime: 2022-07-22 11:00:06
5
+ * @LastEditors: zhangzhenfei
6
+ * @Description: 文件上传
7
+ */
8
+
9
+ // 对象存储类型
10
+ const UPLOADER_TYPE = {
11
+ ALIYUN: 'ALIYUN', // 阿里云
12
+ TXYUN: 'TXYUN', // 腾讯云
13
+ HUAWEI: 'HUAWEI' // 华为云
14
+ };
15
+
16
+ const DEFAULT_OPTIONS = {
17
+ // type: UPLOADER_TYPE.ALIYUN, //
18
+ // accessKeyId: 'LTAIXeOzClQBtKs3',
19
+ // bucketName: 'sadais-oss',
20
+ // endPoint: 'https://oss-cn-hangzhou.aliyuncs.com',
21
+ // path: 'file',
22
+ // signature: '6Y5l5k56y9VgxDU1vhsyCLC99QM=',
23
+ // domain: 'https://m.antibao.cn',
24
+ // policy:'',
25
+ // timeOut: 1642476191415
26
+ };
27
+
28
+ /**
29
+ * @param {String} params.type
30
+ * @param {String} params.getOptionFun
31
+ */
32
+ const UploaderInstance = (function () {
33
+ let instance;
34
+ return function (params) {
35
+ if (!instance) {
36
+ instance = new SadaisUploader(params);
37
+ }
38
+ return instance
39
+ }
40
+ })();
41
+
42
+ class SadaisUploader {
43
+ constructor(params) {
44
+ this._init(params);
45
+ }
46
+
47
+ /**
48
+ * 初始化
49
+ * @param {Object} options
50
+ */
51
+ async _init(params) {
52
+ this.params = params;
53
+ // 不在初始化的时候调用接口,上传文件时再调用,故注释以下代码
54
+ // this._initOptions()
55
+ }
56
+
57
+ /**
58
+ * 获取配置信息
59
+ */
60
+ async initOptions(customParams) {
61
+ if (!this.params) this.params = {};
62
+
63
+ if (customParams) {
64
+ return (this.params = {
65
+ ...this.params,
66
+ ...customParams
67
+ })
68
+ }
69
+ let { type, getOptionFun } = this.params;
70
+
71
+ if (getOptionFun) {
72
+ const options = await getOptionFun(type);
73
+ if (!options) return
74
+ if (options.path && !options.path.endsWith('/')) {
75
+ options.path = options.path + '/';
76
+ }
77
+ this.options = { ...options, type };
78
+ }
79
+ }
80
+
81
+ /**
82
+ * 是否超时
83
+ */
84
+ _isTimeOut() {
85
+ // 比服务器timeOut时间提前10s过期
86
+ const timeout = this.options.timeOut - 1000 * 10;
87
+ return new Date().getTime() > timeout
88
+ }
89
+
90
+ /**
91
+ * 文件上传
92
+ * @param { File | Array<file> } file 文件或文件数组
93
+ */
94
+ async upload(file) {
95
+ if (!file) return
96
+ let files = Array.isArray(file) ? file : [file];
97
+ const result = [];
98
+ for (let i = 0; i < files.length; i++) {
99
+ const item = files[i];
100
+ const { data, head } = await this.uploadFile(item);
101
+ result.push({
102
+ index: i,
103
+ url: data,
104
+ ret: head.ret
105
+ });
106
+ }
107
+ return result
108
+ }
109
+
110
+ /**
111
+ * 单文件上传
112
+ * @param {File} file
113
+ * @return Promise
114
+ */
115
+ async uploadFile(file) {
116
+ if (!this.options || this._isTimeOut()) {
117
+ await this.initOptions();
118
+ }
119
+ if (!file.name && file.path) {
120
+ const isBlobFile = file.path.startsWith('blob');
121
+ const suffix = !isBlobFile ? file.path.substring(file.path.lastIndexOf('.')) : '.png';
122
+ file.name = this._guid() + suffix;
123
+ }
124
+ return new Promise((resolve, reject) => {
125
+ const { domain } = this.options;
126
+
127
+ // 请求地址
128
+ const formData = this._buildParams(file);
129
+
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' }
139
+ };
140
+
141
+ try {
142
+ // uniapp
143
+ uni.uploadFile({
144
+ url: apiUrl,
145
+ filePath: file.path, // uni api提供的blob格式图片地址
146
+ name: 'file',
147
+ formData,
148
+ success: (res) => {
149
+ const { statusCode } = res;
150
+ if (statusCode == 200) {
151
+ resolve(success);
152
+ } else {
153
+ error.head.msg = res;
154
+ reject(error);
155
+ }
156
+ },
157
+ fail: (error) => {
158
+ console.log(error);
159
+ reject(error);
160
+ }
161
+ });
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);
170
+ const xhr = new XMLHttpRequest();
171
+ xhr.open('POST', apiUrl, true);
172
+ xhr.onreadystatechange = () => {
173
+ if (xhr.readyState === XMLHttpRequest.DONE) {
174
+ if (xhr.status === 200) {
175
+ resolve(success);
176
+ } else {
177
+ reject(error);
178
+ }
179
+ }
180
+ };
181
+ xhr.send(data);
182
+ }
183
+ })
184
+ }
185
+
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 }
203
+ }
204
+
205
+ // 按类型组装过参数
206
+ _buildParams(file) {
207
+ const opt = this.options;
208
+ const type = opt.type;
209
+ const params = {
210
+ name: file.name,
211
+ policy: opt.policy,
212
+ success_action_status: '200',
213
+ key: this._getUploadFilePath(file.name)
214
+ };
215
+ const endPoint = opt.endPoint.replace('https://', '').replace('http://', '');
216
+ if (UPLOADER_TYPE.TXYUN === type) {
217
+ params['q-ak'] = opt.accessKeyId;
218
+ params['q-signature'] = opt.signature; // 签名
219
+ params['q-sign-algorithm'] = 'sha1'; // 签名算法
220
+ params['q-key-time'] = opt.param['q-sign-time'];
221
+ // params['q-sign-time'] = opt.param['q-sign-time']
222
+ params.url = `https://${opt.bucketName}.cos.${endPoint}.myqcloud.com`;
223
+ } else if (UPLOADER_TYPE.HUAWEI === type) {
224
+ params.AccessKeyId = opt.accessKeyId;
225
+ params.signature = opt.signature;
226
+ params.url = `https://${opt.bucketName}.obs.${endPoint}.myhuaweicloud.com`;
227
+ } else {
228
+ params.signature = opt.signature;
229
+ params.OSSAccessKeyId = opt.accessKeyId;
230
+ params.bucket = opt.bucketName;
231
+
232
+ params.url = `https://${opt.bucketName}.${endPoint}`;
233
+ }
234
+ return params
235
+ }
236
+
237
+ /**
238
+ * 获取上传文件路径
239
+ * @param {String} name 文件名
240
+ * @returns
241
+ */
242
+ _getUploadFilePath(name) {
243
+ const { useOriginalName, path } = this.options;
244
+ const lastIndexOf = name.lastIndexOf('.');
245
+ const originalName = name.substring(0, lastIndexOf);
246
+ const suffix = name.substring(lastIndexOf + 1);
247
+ const fileName = useOriginalName ? `/${originalName}` : '';
248
+ // 为了保证使用文件原名时,文件不被覆盖,仍然使用随机生成方式
249
+ // ${this._getNowDate()}/
250
+ return `${path}${this._getNowDate()}/${this._guid()}${fileName}.${suffix}`
251
+ }
252
+
253
+ /**
254
+ * 获取当前日期
255
+ * @returns YYYY-MM-DD
256
+ */
257
+ _getNowDate() {
258
+ const date = new Date();
259
+ const year = date.getFullYear();
260
+ let month = date.getMonth() + 1;
261
+ let day = date.getDate();
262
+ if (month < 10) {
263
+ month = `0${month}`;
264
+ }
265
+ if (day < 10) {
266
+ day = `0${day}`;
267
+ }
268
+
269
+ return `${year}${month}${day}`
270
+ }
271
+
272
+ /**
273
+ * 生成guid,用于生成随机文件名
274
+ * @return String
275
+ */
276
+ _guid() {
277
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
278
+ var r = (Math.random() * 16) | 0,
279
+ v = c == 'x' ? r : (r & 0x3) | 0x8;
280
+ return v.toString(16)
281
+ })
282
+ }
278
283
  }
279
284
 
280
285
  export { DEFAULT_OPTIONS, UPLOADER_TYPE, UploaderInstance };
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,u=!0,c=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return u=e.done,e},e:function(e){c=!0,o=e},f:function(){try{u||null==r.return||r.return()}finally{if(c)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 u=e[i](o),c=u.value}catch(e){return void n(e)}u.done?t(c):Promise.resolve(c).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 u(e){i(o,r,a,u,c,"next",e)}function c(e){i(o,r,a,u,c,"throw",e)}u(void 0)}))}}function u(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 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 n,a,i,c,p,l,f,h;return n=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 n,a,i,o;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t&&(this.params.type=t.type||this.params.type,this.params.getOptionFun=t.getOptionFun||this.params.getOptionFun),n=this.params,a=n.type,!(i=n.getOptionFun)){e.next=10;break}return e.next=5,i(a);case 5:if(o=e.sent){e.next=8;break}return e.abrupt("return");case 8:o.path&&!o.path.endsWith("/")&&(o.path=o.path+"/"),this.options=r(r({},o),{},{type:a});case 10: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 n,r,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: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,u=o.data,c=o.head,r.push({index:a,url:u,ret:c.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 l.apply(this,arguments)})},{key:"uploadFile",value:(p=o(regeneratorRuntime.mark((function e(t){var n,r=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&&(n=t.path.substring(t.path.lastIndexOf(".")),t.name=this._guid()+n),e.abrupt("return",new Promise((function(e,n){var a=r.options.domain,i=r._buildParams(t),o=i.url,u={data:"".concat(a).concat(a.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,n(c))},fail:function(e){console.log(e),n(e)}})}catch(r){console.log("uni报错,调用XMLHttpRequest",r);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):n(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(n){var r,a,i,o,u,c,s;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:r=[],a=[],i=e(n),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?r.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:r,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,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 s.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")):s.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.options,n=t.useOriginalName,r=t.path,a=e.lastIndexOf("."),i=e.substring(0,a),o=e.substring(a+1),u=n?"/".concat(i):"";return"".concat(r).concat(this._getNowDate(),"/").concat(this._guid()).concat(u,".").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&&u(n.prototype,a),i&&u(n,i),Object.defineProperty(n,"prototype",{writable:!1}),t}();exports.DEFAULT_OPTIONS={},exports.UPLOADER_TYPE=s,exports.UploaderInstance=p;
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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sadais/uploader",
3
- "version": "0.3.3",
3
+ "version": "0.3.6",
4
4
  "main": "dist/index.min.js",
5
5
  "module": "dist/index.es.js",
6
6
  "keywords": [