@lambo-design-mobile/lambo-js-bridge 1.0.0-beta.38 → 1.0.0-beta.39

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.
@@ -1,383 +1,471 @@
1
1
  /* eslint-disable @typescript-eslint/no-unused-vars */
2
2
  /* eslint-disable no-undef */
3
3
 
4
- import ajax from "@lambo-design-mobile/shared/utils/ajax";
5
- import config from "@lambo-design-mobile/shared/config/config";
4
+ import ajax from '@lambo-design-mobile/shared/utils/ajax';
5
+ import config from '@lambo-design-mobile/shared/config/config';
6
6
  // import coordtransform from "coordtransform";
7
- import { getAddress, initBdMap, getAddressByType, getAxisByType } from './BdMapUtils';
7
+ import {
8
+ getAddress,
9
+ initBdMap,
10
+ getAddressByType,
11
+ getAxisByType,
12
+ } from './BdMapUtils';
8
13
 
9
14
  class WechatAdapter {
10
- constructor(_options) {
11
- this.appId = _options.wechatId; // 保存 appId 以便在 getInitInfo 中使用
12
- // if (!window.wx) {
13
- // const script = document.createElement('script');
14
- // script.src = "//res.wx.qq.com/open/js/jweixin-1.6.0.js";
15
- // document.head.appendChild(script);
16
- // }
17
- function loadScript(src) {
18
- return new Promise((resolve, reject) => {
19
- const script = document.createElement('script');
20
- script.src = src;
21
- script.onload = () => resolve(script);
22
- script.onerror = () => reject(new Error('Failed to load script'));
23
- document.head.appendChild(script);
24
- });
25
- }
26
- loadScript('//res.wx.qq.com/open/js/jweixin-1.6.0.js')
27
- .then(script => {
28
- console.log('Script loaded');
29
- this.init(_options);
30
- })
31
- .catch(err => console.error(err));
15
+ constructor(_options) {
16
+ this.appId = _options.wechatId; // 保存 appId 以便在 getInitInfo 中使用
17
+ // if (!window.wx) {
18
+ // const script = document.createElement('script');
19
+ // script.src = "//res.wx.qq.com/open/js/jweixin-1.6.0.js";
20
+ // document.head.appendChild(script);
21
+ // }
22
+ function loadScript(src) {
23
+ return new Promise((resolve, reject) => {
24
+ const script = document.createElement('script');
25
+ script.src = src;
26
+ script.onload = () => resolve(script);
27
+ script.onerror = () => reject(new Error('Failed to load script'));
28
+ document.head.appendChild(script);
29
+ });
32
30
  }
31
+ loadScript('//res.wx.qq.com/open/js/jweixin-1.6.0.js')
32
+ .then((script) => {
33
+ console.log('Script loaded');
34
+ this.init(_options);
35
+ })
36
+ .catch((err) => console.error(err));
37
+ }
33
38
 
34
- async init(options) {
35
- const currentUrl = encodeURIComponent(window.location.href.split('#')[0]); // 确保URL编码且去除hash部分
36
- ajax.request({
37
- url: `${config.upmsServerContext}/manage/ibpWxMpBaseinfo/gtJsTicket?appId=${options.wechatId}&url=${currentUrl}`,
38
- method: 'get'
39
- }).then((resp) => {
40
- if (resp.data.code === 1) {
41
- const { data } = resp.data;
42
- window.wx.config({
43
- debug: false, // 开启调试模式
44
- appId: data.appId, // 必填,公众号的唯一标识
45
- timestamp: data.timestamp, // 必填,生成签名的时间戳
46
- nonceStr: data.noncestr, // 必填,生成签名的随机串
47
- signature: data.signature, // 必填,签名
48
- jsApiList: ['getLocation', 'scanQRCode', 'chooseImage', 'getLocalImgData', 'openLocation'] // 必填,需要使用的JS接口列表
49
- });
39
+ async init(options) {
40
+ const currentUrl = encodeURIComponent(window.location.href.split('#')[0]); // 确保URL编码且去除hash部分
41
+ ajax
42
+ .request({
43
+ url: `${config.upmsServerContext}/manage/ibpWxMpBaseinfo/gtJsTicket?appId=${options.wechatId}&url=${currentUrl}`,
44
+ method: 'get',
45
+ })
46
+ .then((resp) => {
47
+ if (resp.data.code === 1) {
48
+ const { data } = resp.data;
49
+ window.wx.config({
50
+ debug: false, // 开启调试模式
51
+ appId: data.appId, // 必填,公众号的唯一标识
52
+ timestamp: data.timestamp, // 必填,生成签名的时间戳
53
+ nonceStr: data.noncestr, // 必填,生成签名的随机串
54
+ signature: data.signature, // 必填,签名
55
+ jsApiList: [
56
+ 'getLocation',
57
+ 'scanQRCode',
58
+ 'chooseImage',
59
+ 'getLocalImgData',
60
+ 'openLocation',
61
+ ], // 必填,需要使用的JS接口列表
62
+ });
50
63
 
51
- window.wx.error(function (res) {
52
- console.log("error:", res);
53
- console.error(res);
54
- });
64
+ window.wx.error(function (res) {
65
+ console.log('error:', res);
66
+ console.error(res);
67
+ });
55
68
 
56
- wx.ready(function() {
57
- console.log("ready...");
58
- // config信息验证后会执行ready方法
59
- // 可以在这里调用相关接口
60
- });
61
- }
62
- }).catch((err) => {
63
- console.error(err);
64
- });
65
- }
69
+ wx.ready(function () {
70
+ console.log('ready...');
71
+ // config信息验证后会执行ready方法
72
+ // 可以在这里调用相关接口
73
+ });
74
+ }
75
+ })
76
+ .catch((err) => {
77
+ console.error(err);
78
+ });
79
+ }
66
80
 
67
- async getLocation(options) {
68
- return new Promise((resolve, reject) => {
69
- wx.ready(async () => {
70
- // 解决在 URL 变化时,由于 wx.config 和 wx.ready 的异步特性导致的微信接口调用使用旧配置、签名失效或调用失败的问题
71
- // 新增重试机制检查接口可用性
72
- let retryInterval;
73
- try {
74
- await new Promise((retryResolve, retryReject) => {
75
- let retryCount = 0;
76
- const maxRetries = 30; // 最大重试次数 (30*100ms=3秒超时)
77
- retryInterval = setInterval(async () => {
78
- if (retryCount++ >= maxRetries) {
79
- clearInterval(retryInterval);
80
- retryReject(new Error("JS-SDK接口初始化超时"));
81
- return;
82
- }
81
+ /**
82
+ * 获取定位
83
+ * 2025-11-28 15:49:23 修改,增加审计日志回调函数auditLog,在不同阶段会调用该回调函数,调用参数如下
84
+ * {
85
+ * seg: 阶段,当前有 beforeCheck、checkError、afterCheck、beforeLocation、successLocation、errorLocation1、errorLocation2
86
+ * title: 对阶段的文字描述
87
+ * }
88
+ * 业务系统有需要对定位进行审计的需求,在调用定位的时候,在options中增加auditLog属性,并根据需要记录所需记录日志的阶段或者全部记录
89
+ * @param {*} options
90
+ * @returns
91
+ */
92
+ async getLocation(options) {
93
+ return new Promise((resolve, reject) => {
94
+ wx.ready(async () => {
95
+ // 解决在 URL 变化时,由于 wx.config 和 wx.ready 的异步特性导致的微信接口调用使用旧配置、签名失效或调用失败的问题
96
+ // 新增重试机制检查接口可用性
97
+ let retryInterval;
98
+ if (options.auditLog && options.auditLog instanceof Function) {
99
+ options.auditLog({
100
+ seg: 'beforeCheck',
101
+ title: '开始检测小程序jssdk授权状态',
102
+ });
103
+ }
104
+ try {
105
+ await new Promise((retryResolve, retryReject) => {
106
+ let retryCount = 0;
107
+ const maxRetries = 30; // 最大重试次数 (30*100ms=3秒超时)
108
+ retryInterval = setInterval(async () => {
109
+ if (retryCount++ >= maxRetries) {
110
+ clearInterval(retryInterval);
111
+ retryReject(new Error('JS-SDK接口初始化超时'));
112
+ return;
113
+ }
83
114
 
84
- // 检查getLocation接口是否可用
85
- wx.checkJsApi({
86
- jsApiList: ["getLocation"],
87
- success: (res) => {
88
- if (res.checkResult.getLocation === true) {
89
- clearInterval(retryInterval);
90
- retryResolve();
91
- }
92
- },
93
- fail: () => {/* 失败不计入重试,继续轮询 */
94
- }
95
- });
96
- }, 100); // 每100ms检查一次
97
- });
98
- } catch (error) {
99
- reject(new Error(`接口初始化失败: ${error.message}`));
100
- return;
101
- }
115
+ // 检查getLocation接口是否可用
116
+ wx.checkJsApi({
117
+ jsApiList: ['getLocation'],
118
+ success: (res) => {
119
+ if (res.checkResult.getLocation === true) {
120
+ clearInterval(retryInterval);
121
+ retryResolve();
122
+ }
123
+ },
124
+ fail: () => {
125
+ /* 失败不计入重试,继续轮询 */
126
+ },
127
+ });
128
+ }, 100); // 每100ms检查一次
129
+ });
130
+ } catch (error) {
131
+ reject(new Error(`接口初始化失败: ${error.message}`));
132
+ if (options.auditLog && options.auditLog instanceof Function) {
133
+ options.auditLog({
134
+ seg: 'checkError',
135
+ title: '检测小程序jssdk授权状态异常并中止定位',
136
+ });
137
+ }
138
+ return;
139
+ }
102
140
 
103
- // 检查 options.type,如果为空或者不含有 'wgs84' 'bd09',则设置为 'gcj02'
104
- let locationType = options.type;
105
- if (!options.type || (options.type !== 'wgs84' && options.type !== 'bd09')) {
106
- locationType = 'gcj02';
107
- }
141
+ if (options.auditLog && options.auditLog instanceof Function) {
142
+ options.auditLog({
143
+ seg: 'afterCheck',
144
+ title: '检测小程序jssdk授权状态结束',
145
+ });
146
+ }
108
147
 
109
- const fetchLocation = (type) => {
110
- return new Promise((resolve, reject) => {
111
- wx.getLocation({
112
- ...options,
113
- type: type,
114
- success: location => {
115
- const unifiedLocation = {
116
- latitude: location.latitude || location.lat || null, // 统一纬度属性
117
- longitude: location.longitude || location.lng || null, // 统一经度属性
118
- accuracy: location.accuracy || null // 精确度,如果有的话
119
- };
148
+ // 检查 options.type,如果为空或者不含有 'wgs84' 或 'bd09',则设置为 'gcj02'
149
+ let locationType = options.type;
150
+ if (
151
+ !options.type ||
152
+ (options.type !== 'wgs84' && options.type !== 'bd09')
153
+ ) {
154
+ locationType = 'gcj02';
155
+ }
120
156
 
121
- if (!unifiedLocation.latitude || !unifiedLocation.longitude) {
122
- return reject(new Error('Invalid location data'));
123
- }
124
- // options.needAddress 是否需要地址信息
125
- // if(options.needAddress && !unifiedLocation.address) {
126
- // // 根据坐标得到地址描述
127
- // const res = getAddress(unifiedLocation.longitude, unifiedLocation.latitude)
128
- // unifiedLocation.city = res.addressComponents.city
129
- // unifiedLocation.province = res.addressComponents.province
130
- // unifiedLocation.address = res.address
131
- // }
157
+ const fetchLocation = (type) => {
158
+ return new Promise((resolve, reject) => {
159
+ if (options.auditLog && options.auditLog instanceof Function) {
160
+ options.auditLog({
161
+ seg: 'beforeLocation',
162
+ title: '小程序调用jssdk发起定位',
163
+ });
164
+ }
165
+ wx.getLocation({
166
+ ...options,
167
+ type: type,
168
+ success: (location) => {
169
+ const unifiedLocation = {
170
+ latitude: location.latitude || location.lat || null, // 统一纬度属性
171
+ longitude: location.longitude || location.lng || null, // 统一经度属性
172
+ accuracy: location.accuracy || null, // 精确度,如果有的话
173
+ };
132
174
 
133
- resolve(unifiedLocation);
134
- },
135
- fail: err => {
136
- console.error("getLocation failed:", err);
137
- reject(err);
138
- }
139
- });
175
+ if (options.auditLog && options.auditLog instanceof Function) {
176
+ options.auditLog({
177
+ seg: 'successLocation',
178
+ title:
179
+ '小程序调用jssdk定位成功' +
180
+ JSON.stringify(unifiedLocation),
181
+ });
182
+ }
183
+
184
+ if (!unifiedLocation.latitude || !unifiedLocation.longitude) {
185
+ if (
186
+ options.auditLog &&
187
+ options.auditLog instanceof Function
188
+ ) {
189
+ options.auditLog({
190
+ seg: 'errorLocation1',
191
+ title:
192
+ '小程序调用jssdk定位异常,未取到经纬度'
140
193
  });
141
- };
194
+ }
195
+ return reject(new Error('Invalid location data'));
196
+ }
197
+ // options.needAddress 是否需要地址信息
198
+ // if(options.needAddress && !unifiedLocation.address) {
199
+ // // 根据坐标得到地址描述
200
+ // const res = getAddress(unifiedLocation.longitude, unifiedLocation.latitude)
201
+ // unifiedLocation.city = res.addressComponents.city
202
+ // unifiedLocation.province = res.addressComponents.province
203
+ // unifiedLocation.address = res.address
204
+ // }
142
205
 
143
- // 先判断是否需要地理位置 如不需要 直接返回坐标
144
- if (options.needAddress) {
145
- fetchLocation('gcj02'.then(unifiedLocation => {
146
- const result = getAddressByType(unifiedLocation, locationType)
147
- if (!result) {
148
- return reject(new Error('Invalid location data'));
149
- }
150
- resolve(unifiedLocation);
151
- }))
152
- .catch(err => {
153
- reject(err)
154
- })
155
- } else {
156
- resolve(fetchLocation(locationType))
206
+ resolve(unifiedLocation);
207
+ },
208
+ fail: (err) => {
209
+ console.error('getLocation failed:', err);
210
+ if (options.auditLog && options.auditLog instanceof Function) {
211
+ options.auditLog({
212
+ seg: 'errorLocation2',
213
+ title: '小程序调用jssdk定位异常,' + JSON.stringify(err),
214
+ });
157
215
  }
216
+ reject(err);
217
+ },
218
+ });
219
+ });
220
+ };
158
221
 
159
- // // 先取gcj02 再根据type转成不同坐标系
160
- // fetchLocation('gcj02').then(unifiedLocation => {
161
- // // options.needAddress 是否需要地址信息
162
- // if(options.needAddress && !unifiedLocation.address) {
163
- // const result = getAddressByType(unifiedLocation, locationType)
164
- // if(!result) {
165
- // return reject(new Error('Invalid location data'));
166
- // }
167
- // resolve(unifiedLocation);
168
- // }
169
- // else {
170
- // const result = getAxisByType(unifiedLocation, locationType)
171
- // if(!result) {
172
- // return reject(new Error('Invalid location data'));
173
- // }
174
- // resolve(unifiedLocation);
175
- // }
176
- // }).catch(err => {
177
- // reject(err);
178
- // });
222
+ // 先判断是否需要地理位置 如不需要 直接返回坐标
223
+ if (options.needAddress) {
224
+ fetchLocation(
225
+ 'gcj02'.then((unifiedLocation) => {
226
+ const result = getAddressByType(unifiedLocation, locationType);
227
+ if (!result) {
228
+ return reject(new Error('Invalid location data'));
229
+ }
230
+ resolve(unifiedLocation);
231
+ })
232
+ ).catch((err) => {
233
+ reject(err);
234
+ });
235
+ } else {
236
+ resolve(fetchLocation(locationType));
237
+ }
179
238
 
239
+ // // 先取gcj02 再根据type转成不同坐标系
240
+ // fetchLocation('gcj02').then(unifiedLocation => {
241
+ // // options.needAddress 是否需要地址信息
242
+ // if(options.needAddress && !unifiedLocation.address) {
243
+ // const result = getAddressByType(unifiedLocation, locationType)
244
+ // if(!result) {
245
+ // return reject(new Error('Invalid location data'));
246
+ // }
247
+ // resolve(unifiedLocation);
248
+ // }
249
+ // else {
250
+ // const result = getAxisByType(unifiedLocation, locationType)
251
+ // if(!result) {
252
+ // return reject(new Error('Invalid location data'));
253
+ // }
254
+ // resolve(unifiedLocation);
255
+ // }
256
+ // }).catch(err => {
257
+ // reject(err);
258
+ // });
180
259
 
181
- // if (locationType === 'bd09') {
182
- // // 先获取 gcj02 坐标
183
- // fetchLocation('gcj02').then(unifiedLocation => {
184
- // // 将 gcj02 坐标转换为 bd09
185
- // const [bd09Lng, bd09Lat] = coordtransform.gcj02tobd09(unifiedLocation.longitude, unifiedLocation.latitude);
186
- // unifiedLocation.longitude = bd09Lng;
187
- // unifiedLocation.latitude = bd09Lat;
188
- // if (!unifiedLocation.latitude || !unifiedLocation.longitude) {
189
- // return reject(new Error('Invalid location data'));
190
- // }
191
- // // options.needAddress 是否需要地址信息
192
- // if(options.needAddress && !unifiedLocation.address) {
193
- // // 根据坐标得到地址描述
194
- // const res = getAddress(unifiedLocation.longitude, unifiedLocation.latitude)
195
- // unifiedLocation.city = res.addressComponents.city
196
- // unifiedLocation.province = res.addressComponents.province
197
- // unifiedLocation.address = res.address
198
- // }
260
+ // if (locationType === 'bd09') {
261
+ // // 先获取 gcj02 坐标
262
+ // fetchLocation('gcj02').then(unifiedLocation => {
263
+ // // 将 gcj02 坐标转换为 bd09
264
+ // const [bd09Lng, bd09Lat] = coordtransform.gcj02tobd09(unifiedLocation.longitude, unifiedLocation.latitude);
265
+ // unifiedLocation.longitude = bd09Lng;
266
+ // unifiedLocation.latitude = bd09Lat;
267
+ // if (!unifiedLocation.latitude || !unifiedLocation.longitude) {
268
+ // return reject(new Error('Invalid location data'));
269
+ // }
270
+ // // options.needAddress 是否需要地址信息
271
+ // if(options.needAddress && !unifiedLocation.address) {
272
+ // // 根据坐标得到地址描述
273
+ // const res = getAddress(unifiedLocation.longitude, unifiedLocation.latitude)
274
+ // unifiedLocation.city = res.addressComponents.city
275
+ // unifiedLocation.province = res.addressComponents.province
276
+ // unifiedLocation.address = res.address
277
+ // }
199
278
 
200
- // resolve(unifiedLocation);
201
- // }).catch(err => {
202
- // reject(err);
203
- // });
204
- // }
205
- });
206
- });
207
- }
279
+ // resolve(unifiedLocation);
280
+ // }).catch(err => {
281
+ // reject(err);
282
+ // });
283
+ // }
284
+ });
285
+ });
286
+ }
208
287
 
209
- async openLocation(options) {
210
- return new Promise((resolve, reject) => {
211
- wx.ready(() => {
212
- wx.openLocation({
213
- latitude: options.latitude,
214
- longitude: options.longitude,
215
- name: options.name || '',
216
- address: options.address || '',
217
- scale: options.scale || 1,
218
- infoUrl: options.infoUrl || '',
219
- success: () => {
220
- console.log("openLocation success");
221
- resolve();
222
- },
223
- fail: err => {
224
- console.error("openLocation failed:", err);
225
- reject(err);
226
- }
227
- });
228
- });
288
+ async openLocation(options) {
289
+ return new Promise((resolve, reject) => {
290
+ wx.ready(() => {
291
+ wx.openLocation({
292
+ latitude: options.latitude,
293
+ longitude: options.longitude,
294
+ name: options.name || '',
295
+ address: options.address || '',
296
+ scale: options.scale || 1,
297
+ infoUrl: options.infoUrl || '',
298
+ success: () => {
299
+ console.log('openLocation success');
300
+ resolve();
301
+ },
302
+ fail: (err) => {
303
+ console.error('openLocation failed:', err);
304
+ reject(err);
305
+ },
229
306
  });
230
- }
307
+ });
308
+ });
309
+ }
231
310
 
232
- async scanCode(options) {
233
- return new Promise((resolve, reject) => {
234
- wx.ready(() => {
235
- wx.scanQRCode({
236
- ...options,
237
- needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果
238
- success: (res) => {
239
- console.log("scanQRCode success:", res);
240
- resolve( res); // 当needResult 为 1 时,扫码返回的结果
241
- },
242
- fail: (err) => {
243
- console.error("scanQRCode failed:", err);
244
- reject(err);
245
- }
246
- });
247
- });
311
+ async scanCode(options) {
312
+ return new Promise((resolve, reject) => {
313
+ wx.ready(() => {
314
+ wx.scanQRCode({
315
+ ...options,
316
+ needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果
317
+ success: (res) => {
318
+ console.log('scanQRCode success:', res);
319
+ resolve(res); // 当needResult 为 1 时,扫码返回的结果
320
+ },
321
+ fail: (err) => {
322
+ console.error('scanQRCode failed:', err);
323
+ reject(err);
324
+ },
248
325
  });
249
- }
250
-
251
- async takePhoto(options) {
252
- return new Promise((resolve, reject) => {
253
- wx.ready(() => {
254
- wx.chooseImage({
255
- ...options,
256
- // count: options.count || 1, // 可以根据传入的options设置选择图片的数量
257
- // sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
258
- // sourceType: ['camera','album'], // 可以指定来源是相册还是相机,默认二者都有
259
- success: async (res) => {
260
- const localIds = res.localIds; // 返回选定照片的本地ID数组
261
- const results = [];
326
+ });
327
+ });
328
+ }
262
329
 
263
- for (const localId of localIds) {
264
- const result = { localId }; // 存储每张照片的处理结果
265
- if (!options.outputType) {
266
- // outputType为空,返回所有结果
267
- await new Promise((resolve, reject) => {
268
- wx.getLocalImgData({
269
- localId,
270
- success: (dataRes) => {
271
- result.imageData = dataRes.localData;
272
- resolve();
273
- },
274
- fail: (err) => {
275
- console.error("getLocalImgData failed:", err);
276
- reject(err);
277
- }
278
- });
279
- });
280
- } else {
281
- if (options.outputType.includes('info')) {
282
- result.imageInfo = localId;
283
- }
284
- if (options.outputType.includes('data')) {
285
- await new Promise((resolve, reject) => {
286
- wx.getLocalImgData({
287
- localId,
288
- success: (dataRes) => {
289
- result.imageData = dataRes.localData;
290
- resolve();
291
- },
292
- fail: (err) => {
293
- console.error("getLocalImgData failed:", err);
294
- reject(err);
295
- }
296
- });
297
- });
298
- }
299
- if (options.outputType.includes('oss')) {
300
- await new Promise((resolve, reject) => {
301
- wx.getLocalImgData({
302
- localId,
303
- success: (dataRes) => {
304
- const file = this.dataURLtoFile(dataRes.localData, 'image.png');
305
- this.uploadToOSS(file, options).then((ossResult) => {
306
- result.imageOss = ossResult;
307
- resolve();
308
- }).catch((err) => {
309
- console.error("uploadToOSS failed:", err);
310
- reject(err);
311
- });
312
- },
313
- fail: (err) => {
314
- console.error("getLocalImgData failed:", err);
315
- reject(err);
316
- }
317
- });
318
- });
319
- }
320
- }
321
- results.push(result); // 将处理结果添加到数组中
322
- }
330
+ async takePhoto(options) {
331
+ return new Promise((resolve, reject) => {
332
+ wx.ready(() => {
333
+ wx.chooseImage({
334
+ ...options,
335
+ // count: options.count || 1, // 可以根据传入的options设置选择图片的数量
336
+ // sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
337
+ // sourceType: ['camera','album'], // 可以指定来源是相册还是相机,默认二者都有
338
+ success: async (res) => {
339
+ const localIds = res.localIds; // 返回选定照片的本地ID数组
340
+ const results = [];
323
341
 
324
- resolve(results); // 返回所有照片的处理结果
342
+ for (const localId of localIds) {
343
+ const result = { localId }; // 存储每张照片的处理结果
344
+ if (!options.outputType) {
345
+ // outputType为空,返回所有结果
346
+ await new Promise((resolve, reject) => {
347
+ wx.getLocalImgData({
348
+ localId,
349
+ success: (dataRes) => {
350
+ result.imageData = dataRes.localData;
351
+ resolve();
325
352
  },
326
353
  fail: (err) => {
327
- console.error("chooseImage failed:", err);
328
- reject(err);
329
- }
354
+ console.error('getLocalImgData failed:', err);
355
+ reject(err);
356
+ },
357
+ });
330
358
  });
331
- });
332
- });
333
- }
359
+ } else {
360
+ if (options.outputType.includes('info')) {
361
+ result.imageInfo = localId;
362
+ }
363
+ if (options.outputType.includes('data')) {
364
+ await new Promise((resolve, reject) => {
365
+ wx.getLocalImgData({
366
+ localId,
367
+ success: (dataRes) => {
368
+ result.imageData = dataRes.localData;
369
+ resolve();
370
+ },
371
+ fail: (err) => {
372
+ console.error('getLocalImgData failed:', err);
373
+ reject(err);
374
+ },
375
+ });
376
+ });
377
+ }
378
+ if (options.outputType.includes('oss')) {
379
+ await new Promise((resolve, reject) => {
380
+ wx.getLocalImgData({
381
+ localId,
382
+ success: (dataRes) => {
383
+ const file = this.dataURLtoFile(
384
+ dataRes.localData,
385
+ 'image.png'
386
+ );
387
+ this.uploadToOSS(file, options)
388
+ .then((ossResult) => {
389
+ result.imageOss = ossResult;
390
+ resolve();
391
+ })
392
+ .catch((err) => {
393
+ console.error('uploadToOSS failed:', err);
394
+ reject(err);
395
+ });
396
+ },
397
+ fail: (err) => {
398
+ console.error('getLocalImgData failed:', err);
399
+ reject(err);
400
+ },
401
+ });
402
+ });
403
+ }
404
+ }
405
+ results.push(result); // 将处理结果添加到数组中
406
+ }
334
407
 
408
+ resolve(results); // 返回所有照片的处理结果
409
+ },
410
+ fail: (err) => {
411
+ console.error('chooseImage failed:', err);
412
+ reject(err);
413
+ },
414
+ });
415
+ });
416
+ });
417
+ }
335
418
 
336
- dataURLtoFile(dataurl, filename) {
337
- let arr = dataurl.split(',');
338
- let mime;
339
- if (arr[0].indexOf(':') !== -1) {
340
- mime = arr[0].match(/:(.*?);/)[1];
341
- } else {
342
- mime = 'application/octet-stream'; // 默认MIME类型
343
- }
344
- let bstr = atob(arr[1] || arr[0]);
345
- let n = bstr.length;
346
- let u8arr = new Uint8Array(n);
347
- while (n--) {
348
- u8arr[n] = bstr.charCodeAt(n);
349
- }
350
- return new File([u8arr], filename, {type: mime});
419
+ dataURLtoFile(dataurl, filename) {
420
+ let arr = dataurl.split(',');
421
+ let mime;
422
+ if (arr[0].indexOf(':') !== -1) {
423
+ mime = arr[0].match(/:(.*?);/)[1];
424
+ } else {
425
+ mime = 'application/octet-stream'; // 默认MIME类型
426
+ }
427
+ let bstr = atob(arr[1] || arr[0]);
428
+ let n = bstr.length;
429
+ let u8arr = new Uint8Array(n);
430
+ while (n--) {
431
+ u8arr[n] = bstr.charCodeAt(n);
351
432
  }
433
+ return new File([u8arr], filename, { type: mime });
434
+ }
352
435
 
353
- uploadToOSS(file, options) {
354
- return new Promise((resolve, reject) => {
355
- let formData = new FormData();
356
- formData.append('file', file);
357
- ajax.post(options.ossServerContext + options.ossImgPutUrl, formData, { payload : true }).then(response => {
358
- if (response.data.code === 1) {
359
- const result = response.data.data;
360
- if (result.length > 0) {
361
- resolve(result[0]);
362
- } else {
363
- reject(new Error('No fileId returned'));
364
- }
365
- } else {
366
- reject(new Error('Upload failed'));
367
- }
368
- }).catch(error =>{
369
- reject(error);
370
- });
436
+ uploadToOSS(file, options) {
437
+ return new Promise((resolve, reject) => {
438
+ let formData = new FormData();
439
+ formData.append('file', file);
440
+ ajax
441
+ .post(options.ossServerContext + options.ossImgPutUrl, formData, {
442
+ payload: true,
443
+ })
444
+ .then((response) => {
445
+ if (response.data.code === 1) {
446
+ const result = response.data.data;
447
+ if (result.length > 0) {
448
+ resolve(result[0]);
449
+ } else {
450
+ reject(new Error('No fileId returned'));
451
+ }
452
+ } else {
453
+ reject(new Error('Upload failed'));
454
+ }
455
+ })
456
+ .catch((error) => {
457
+ reject(error);
371
458
  });
372
- }
459
+ });
460
+ }
373
461
 
374
- async getPlatform(options = {}) {
375
- // 获取初始化信息
376
- return {
377
- appId: this.appId,
378
- platform: 'Wechat'
379
- };
380
- }
462
+ async getPlatform(options = {}) {
463
+ // 获取初始化信息
464
+ return {
465
+ appId: this.appId,
466
+ platform: 'Wechat',
467
+ };
468
+ }
381
469
  }
382
470
 
383
471
  export default WechatAdapter;