@haluo/util 2.1.4 → 2.1.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.
@@ -44,11 +44,58 @@
44
44
  * })
45
45
  * ```
46
46
  */
47
+ var __assign = (this && this.__assign) || function () {
48
+ __assign = Object.assign || function(t) {
49
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
50
+ s = arguments[i];
51
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
52
+ t[p] = s[p];
53
+ }
54
+ return t;
55
+ };
56
+ return __assign.apply(this, arguments);
57
+ };
58
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
59
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
60
+ return new (P || (P = Promise))(function (resolve, reject) {
61
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
62
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
63
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
64
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
65
+ });
66
+ };
67
+ var __generator = (this && this.__generator) || function (thisArg, body) {
68
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
69
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
70
+ function verb(n) { return function (v) { return step([n, v]); }; }
71
+ function step(op) {
72
+ if (f) throw new TypeError("Generator is already executing.");
73
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
74
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
75
+ if (y = 0, t) op = [op[0] & 2, t.value];
76
+ switch (op[0]) {
77
+ case 0: case 1: t = op; break;
78
+ case 4: _.label++; return { value: op[1], done: false };
79
+ case 5: _.label++; y = op[1]; op = [0]; continue;
80
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
81
+ default:
82
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
83
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
84
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
85
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
86
+ if (t[2]) _.ops.pop();
87
+ _.trys.pop(); continue;
88
+ }
89
+ op = body.call(thisArg, _);
90
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
91
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
92
+ }
93
+ };
47
94
  import lrz from 'lrz';
48
95
  import { createTracker } from '../track';
49
96
  // ==================== 常量定义 ====================
50
97
  /** 支持的图片格式 */
51
- const SUPPORTED_IMAGE_TYPES = [
98
+ var SUPPORTED_IMAGE_TYPES = [
52
99
  'image/jpeg',
53
100
  'image/png',
54
101
  'image/gif',
@@ -58,7 +105,7 @@ const SUPPORTED_IMAGE_TYPES = [
58
105
  'image/tiff',
59
106
  ];
60
107
  /** 支持的图片格式 ext */
61
- const SUPPORTED_IMAGE_EXTS = [
108
+ var SUPPORTED_IMAGE_EXTS = [
62
109
  'jpg',
63
110
  'jpeg',
64
111
  'png',
@@ -69,15 +116,15 @@ const SUPPORTED_IMAGE_EXTS = [
69
116
  'tiff',
70
117
  ];
71
118
  /** 小图片阈值(KB) */
72
- const SMALL_IMAGE_THRESHOLD = 100;
119
+ var SMALL_IMAGE_THRESHOLD = 100;
73
120
  /** 长图宽高比阈值 */
74
- const LONG_IMAGE_RATIO = 2;
121
+ var LONG_IMAGE_RATIO = 2;
75
122
  /** 默认文件大小限制(MB) */
76
- const DEFAULT_FILE_SIZE_LIMIT = 10;
123
+ var DEFAULT_FILE_SIZE_LIMIT = 10;
77
124
  /** 默认压缩质量 */
78
- const DEFAULT_QUALITY = 0.7;
125
+ var DEFAULT_QUALITY = 0.7;
79
126
  /** 预签名URL过期时间(毫秒) */
80
- const PRESIGNED_URL_EXPIRE_TIME = 60000;
127
+ var PRESIGNED_URL_EXPIRE_TIME = 60000;
81
128
  // ==================== 枚举定义 ====================
82
129
  /**
83
130
  * 业务类型枚举
@@ -149,7 +196,7 @@ export var BusinessType;
149
196
  /**
150
197
  * bucket 图片类型后缀枚举
151
198
  */
152
- export const SuffixEnum = {
199
+ export var SuffixEnum = {
153
200
  nowater: '!nowater',
154
201
  official: '!official',
155
202
  panoram: '!panoram',
@@ -188,11 +235,360 @@ function getFileSizeInMB(size) {
188
235
  * 阿里云OSS上传类
189
236
  * 整合所有项目的aliOss业务逻辑,通过依赖注入实现业务API解耦
190
237
  */
191
- export class AliOssClass {
192
- static instance = null;
193
- apiConfig;
194
- tracker = null;
195
- constructor(apiConfig) {
238
+ var AliOssClass = /** @class */ (function () {
239
+ function AliOssClass(apiConfig) {
240
+ var _this = this;
241
+ this.tracker = null;
242
+ /**
243
+ * 图片上传主方法
244
+ * 整合了所有项目的图片上传逻辑
245
+ * @param option 上传选项
246
+ * @returns Promise - 成功时返回图片信息对象,失败时reject错误信息字符串
247
+ * @returns 成功返回结构: {
248
+ * url: string - 上传后的图片URL,
249
+ * imgUrl: string - 上传后的图片URL(可能包含尺寸信息),
250
+ * imgOrgUrl: string - 原始图片URL(包含尺寸信息),
251
+ * name: string - 文件名,
252
+ * fileName: string - 文件名
253
+ * }
254
+ * @returns 失败返回: 错误信息字符串,如"文件类型不支持"、"上传失败"等
255
+ */
256
+ this.ossUploadImage = function (option) { return __awaiter(_this, void 0, void 0, function () {
257
+ var file, callbacks;
258
+ var _this = this;
259
+ var _a, _b;
260
+ return __generator(this, function (_c) {
261
+ if (!(option.file instanceof File)) {
262
+ return [2 /*return*/, Promise.reject('file is not instanceof File')];
263
+ }
264
+ if (!option.businessType) {
265
+ return [2 /*return*/, Promise.reject('businessType不能为空')];
266
+ }
267
+ file = option.file;
268
+ callbacks = {
269
+ onError: option.onError || (function () { }),
270
+ onSuccess: option.onSuccess || (function () { }),
271
+ onProgress: option.onProgress || (function () { }),
272
+ };
273
+ option.onError = callbacks.onError;
274
+ option.onSuccess = callbacks.onSuccess;
275
+ option.onProgress = callbacks.onProgress;
276
+ // 文件类型验证
277
+ if (!isSupportedImageType(file.type)) {
278
+ callbacks.onError('');
279
+ (_b = (_a = this.apiConfig).messageWarning) === null || _b === void 0 ? void 0 : _b.call(_a, '上传失败,请上传后缀为png、gif、jpg的文件');
280
+ return [2 /*return*/, Promise.reject('文件类型不支持')];
281
+ }
282
+ return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
283
+ var isSmallImage, quality, businessType, res, res, rst, isLong, postFile, imgSize, maxSizeMB, errorMsg, result, res, error_1, errorMsg;
284
+ return __generator(this, function (_a) {
285
+ switch (_a.label) {
286
+ case 0:
287
+ _a.trys.push([0, 12, , 13]);
288
+ isSmallImage = getFileSizeInKB(file.size) <= SMALL_IMAGE_THRESHOLD;
289
+ quality = isSmallImage ? 1 : option.quality || DEFAULT_QUALITY;
290
+ businessType = option.businessType;
291
+ if (!(businessType === BusinessType.CREDIT)) return [3 /*break*/, 2];
292
+ return [4 /*yield*/, this.upload({
293
+ file: file,
294
+ businessType: businessType,
295
+ resolve: resolve,
296
+ reject: reject,
297
+ callbacks: callbacks,
298
+ })];
299
+ case 1: return [2 /*return*/, _a.sent()];
300
+ case 2:
301
+ if (!(option.batchTransfer && this.apiConfig.multiTransferImage)) return [3 /*break*/, 4];
302
+ return [4 /*yield*/, this.apiConfig.multiTransferImage({ file: file })];
303
+ case 3:
304
+ res = _a.sent();
305
+ if (res.data.code === 0) {
306
+ // 盲水印兼容报错
307
+ if (res.data.data) {
308
+ this.loadImage({
309
+ url: res.data.data,
310
+ val: res.data,
311
+ option: option,
312
+ file: file,
313
+ resolve: resolve,
314
+ reject: reject,
315
+ });
316
+ }
317
+ }
318
+ else {
319
+ callbacks.onError('上传失败');
320
+ reject('上传失败');
321
+ this.reportError('批量转换水印上传失败', { type: 'batchTransfer', businessType: businessType });
322
+ }
323
+ return [2 /*return*/];
324
+ case 4:
325
+ if (!(option.imageType === 'carport' &&
326
+ this.apiConfig.darkWaterUploadImage)) return [3 /*break*/, 6];
327
+ return [4 /*yield*/, this.apiConfig.darkWaterUploadImage({ file: file })];
328
+ case 5:
329
+ res = _a.sent();
330
+ if (res.data.code === 0) {
331
+ this.loadImage({
332
+ url: res.data.data,
333
+ val: res.data,
334
+ option: option,
335
+ file: file,
336
+ resolve: resolve,
337
+ reject: reject,
338
+ });
339
+ }
340
+ else {
341
+ callbacks.onError('上传失败');
342
+ reject('上传失败');
343
+ this.reportError('暗水印上传失败', { type: 'darkWater', businessType: businessType });
344
+ }
345
+ return [2 /*return*/];
346
+ case 6: return [4 /*yield*/, lrz(file, { quality: quality })
347
+ // 注释:长图压缩有问题,长宽比>2:1的图片不压缩
348
+ ];
349
+ case 7:
350
+ rst = _a.sent();
351
+ return [4 /*yield*/, this.isLongImage(file)];
352
+ case 8:
353
+ isLong = (_a.sent()) || false;
354
+ postFile = void 0;
355
+ if (option.notCompress || file.type === 'image/gif' || isLong) {
356
+ // 注释:GIF、notCompress选项或长图不压缩
357
+ postFile = file;
358
+ }
359
+ else {
360
+ postFile = rst.file;
361
+ }
362
+ imgSize = postFile.size;
363
+ maxSizeMB = DEFAULT_FILE_SIZE_LIMIT;
364
+ if (getFileSizeInMB(imgSize) > maxSizeMB) {
365
+ errorMsg = "\u56FE\u7247\u4E0D\u80FD\u8D85\u8FC7".concat(maxSizeMB, "M");
366
+ callbacks.onError(errorMsg);
367
+ reject(errorMsg);
368
+ return [2 /*return*/];
369
+ }
370
+ // 设置文件名(确保压缩后的文件有名称)
371
+ if (!postFile.name) {
372
+ Object.defineProperty(postFile, 'name', {
373
+ value: file.name,
374
+ writable: false,
375
+ });
376
+ }
377
+ return [4 /*yield*/, this.upload({
378
+ file: file,
379
+ businessType: businessType,
380
+ resolve: resolve,
381
+ reject: reject,
382
+ callbacks: callbacks,
383
+ })
384
+ // 注释:idCard场景 - 生成预签名URL
385
+ ];
386
+ case 9:
387
+ result = _a.sent();
388
+ if (!((option.idCard || false) &&
389
+ this.apiConfig.generatePrePresignedUrl)) return [3 /*break*/, 11];
390
+ return [4 /*yield*/, this.apiConfig.generatePrePresignedUrl({
391
+ objectId: result.name,
392
+ expireMils: PRESIGNED_URL_EXPIRE_TIME,
393
+ })];
394
+ case 10:
395
+ res = _a.sent();
396
+ if (res.data.code === 0) {
397
+ this.loadImage({
398
+ url: res.data.data,
399
+ val: result,
400
+ file: postFile,
401
+ option: option,
402
+ resolve: resolve,
403
+ reject: reject,
404
+ });
405
+ }
406
+ else {
407
+ callbacks.onError('生成预签名URL失败');
408
+ reject('生成预签名URL失败');
409
+ this.reportError('生成预签名URL失败', { type: 'preSignedUrl', businessType: businessType });
410
+ }
411
+ return [2 /*return*/];
412
+ case 11: return [3 /*break*/, 13];
413
+ case 12:
414
+ error_1 = _a.sent();
415
+ errorMsg = error_1.message || error_1.msg || '上传异常';
416
+ callbacks.onError(errorMsg);
417
+ reject(errorMsg);
418
+ this.reportError(errorMsg, { type: 'ossUploadImage', businessType: option.businessType });
419
+ return [3 /*break*/, 13];
420
+ case 13: return [2 /*return*/];
421
+ }
422
+ });
423
+ }); })];
424
+ });
425
+ }); };
426
+ /**
427
+ * 文件上传方法
428
+ * 支持视频、文档、APK等文件类型
429
+ * @param option 上传选项
430
+ * @returns Promise - 成功时返回文件信息对象,失败时reject错误信息字符串
431
+ * @returns 成功返回结构: {
432
+ * url: string - 上传后的文件URL,
433
+ * imgUrl: string - 上传后的文件URL,
434
+ * imgOrgUrl: string - 上传后的文件URL,
435
+ * name: string - 文件名,
436
+ * fileName: string - 文件名
437
+ * }
438
+ * @returns 失败返回: 错误信息字符串,如"文件类型不支持"、"上传失败"等
439
+ */
440
+ this.ossUploadFile = function (option) { return __awaiter(_this, void 0, void 0, function () {
441
+ var file, callbacks;
442
+ var _this = this;
443
+ return __generator(this, function (_a) {
444
+ if (!(option.file instanceof File)) {
445
+ return [2 /*return*/, Promise.reject('file is not instanceof File')];
446
+ }
447
+ if (!option.businessType) {
448
+ return [2 /*return*/, Promise.reject('businessType不能为空')];
449
+ }
450
+ file = option.file;
451
+ callbacks = {
452
+ onError: option.onError || (function () { }),
453
+ onSuccess: option.onSuccess || (function () { }),
454
+ onProgress: option.onProgress || (function () { }),
455
+ };
456
+ option.onError = callbacks.onError;
457
+ option.onSuccess = callbacks.onSuccess;
458
+ option.onProgress = callbacks.onProgress;
459
+ return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
460
+ var businessType, error_2, errorMsg;
461
+ return __generator(this, function (_a) {
462
+ switch (_a.label) {
463
+ case 0:
464
+ _a.trys.push([0, 2, , 3]);
465
+ businessType = option.businessType;
466
+ return [4 /*yield*/, this.upload({
467
+ file: file,
468
+ businessType: businessType,
469
+ resolve: resolve,
470
+ reject: reject,
471
+ callbacks: callbacks,
472
+ })];
473
+ case 1:
474
+ _a.sent();
475
+ return [3 /*break*/, 3];
476
+ case 2:
477
+ error_2 = _a.sent();
478
+ errorMsg = error_2.message || error_2.msg || '上传异常';
479
+ callbacks.onError(errorMsg);
480
+ reject(errorMsg);
481
+ this.reportError(errorMsg, { type: 'ossUploadFile', businessType: option.businessType });
482
+ return [3 /*break*/, 3];
483
+ case 3: return [2 /*return*/];
484
+ }
485
+ });
486
+ }); })];
487
+ });
488
+ }); };
489
+ /**
490
+ * 纯图片上传 pureOssUploadImage
491
+ * 注释:图片上传,不压缩
492
+ * @param option 上传选项
493
+ * @returns Promise - 成功时返回图片信息对象,失败时reject错误信息字符串
494
+ * @returns 成功返回结构: {
495
+ * url: string - 上传后的图片URL,
496
+ * imgUrl: string - 上传后的图片URL,
497
+ * imgOrgUrl: string - 上传后的图片URL,
498
+ * name: string - 文件名,
499
+ * fileName: string - 文件名
500
+ * }
501
+ * @returns 失败返回: 错误信息字符串,如"文件类型不支持"、"上传失败"等
502
+ */
503
+ this.pureOssUploadImage = function (option) { return __awaiter(_this, void 0, void 0, function () {
504
+ return __generator(this, function (_a) {
505
+ switch (_a.label) {
506
+ case 0: return [4 /*yield*/, this.shopDetailUpdate(option)];
507
+ case 1: return [2 /*return*/, _a.sent()];
508
+ }
509
+ });
510
+ }); };
511
+ /**
512
+ * 商品详情图片上传(不建议直接使用,请使用 pureOssUploadImage)
513
+ * 注释:图片上传,不压缩
514
+ * @param option 上传选项
515
+ * @returns Promise - 成功时返回图片信息对象,失败时reject错误信息字符串
516
+ * @returns 成功返回结构: {
517
+ * url: string - 上传后的图片URL,
518
+ * imgUrl: string - 上传后的图片URL,
519
+ * imgOrgUrl: string - 上传后的图片URL,
520
+ * name: string - 文件名,
521
+ * fileName: string - 文件名
522
+ * }
523
+ * @returns 失败返回: 错误信息字符串,如"文件类型不支持"、"上传失败"等
524
+ */
525
+ this.shopDetailUpdate = function (option) { return __awaiter(_this, void 0, void 0, function () {
526
+ var file, callbacks;
527
+ var _this = this;
528
+ var _a, _b;
529
+ return __generator(this, function (_c) {
530
+ if (!(option.file instanceof File)) {
531
+ return [2 /*return*/, Promise.reject('file is not instanceof File')];
532
+ }
533
+ if (!option.businessType) {
534
+ return [2 /*return*/, Promise.reject('businessType不能为空')];
535
+ }
536
+ file = option.file;
537
+ callbacks = {
538
+ onError: option.onError || (function () { }),
539
+ onSuccess: option.onSuccess || (function () { }),
540
+ onProgress: option.onProgress || (function () { }),
541
+ };
542
+ option.onError = callbacks.onError;
543
+ option.onSuccess = callbacks.onSuccess;
544
+ option.onProgress = callbacks.onProgress;
545
+ // 文件类型验证
546
+ if (!isSupportedImageType(file.type)) {
547
+ callbacks.onError('');
548
+ (_b = (_a = this.apiConfig).messageWarning) === null || _b === void 0 ? void 0 : _b.call(_a, '上传失败,请上传后缀为png、gif、jpg的文件');
549
+ return [2 /*return*/, Promise.reject('文件类型不支持')];
550
+ }
551
+ return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
552
+ var businessType, errorMsg, error_3, errorMsg;
553
+ return __generator(this, function (_a) {
554
+ switch (_a.label) {
555
+ case 0:
556
+ _a.trys.push([0, 2, , 3]);
557
+ businessType = option.businessType;
558
+ // 文件大小验证
559
+ if (getFileSizeInMB(file.size) > DEFAULT_FILE_SIZE_LIMIT) {
560
+ errorMsg = "\u56FE\u7247\u4E0D\u80FD\u8D85\u8FC7".concat(DEFAULT_FILE_SIZE_LIMIT, "M");
561
+ callbacks.onError(errorMsg);
562
+ reject(errorMsg);
563
+ return [2 /*return*/];
564
+ }
565
+ return [4 /*yield*/, this.upload({
566
+ file: file,
567
+ businessType: businessType,
568
+ resolve: resolve,
569
+ reject: reject,
570
+ callbacks: callbacks,
571
+ })];
572
+ case 1:
573
+ _a.sent();
574
+ return [3 /*break*/, 3];
575
+ case 2:
576
+ error_3 = _a.sent();
577
+ errorMsg = error_3.message || error_3.msg || '上传异常';
578
+ callbacks.onError(errorMsg);
579
+ reject(errorMsg);
580
+ this.reportError(errorMsg, { type: 'pureOssUploadImage', businessType: option.businessType });
581
+ return [3 /*break*/, 3];
582
+ case 3: return [2 /*return*/];
583
+ }
584
+ });
585
+ }); })];
586
+ });
587
+ }); };
588
+ /**
589
+ * 业务类型枚举
590
+ */
591
+ this.businessType = BusinessType;
196
592
  this.apiConfig = apiConfig;
197
593
  // 只有启用错误上报时才创建 tracker 实例
198
594
  if (apiConfig.enableErrorReport) {
@@ -201,43 +597,52 @@ export class AliOssClass {
201
597
  });
202
598
  }
203
599
  }
204
- static getInstance(apiConfig) {
600
+ AliOssClass.getInstance = function (apiConfig) {
205
601
  if (!AliOssClass.instance) {
206
602
  AliOssClass.instance = new AliOssClass(apiConfig);
207
603
  }
208
604
  return AliOssClass.instance;
209
- }
605
+ };
210
606
  /**
211
607
  * 上报上传错误
212
608
  * @param err 错误信息
213
609
  * @param extra 额外信息
214
610
  */
215
- reportError(err, extra) {
611
+ AliOssClass.prototype.reportError = function (err, extra) {
216
612
  // 只有启用错误上报且 tracker 存在时才上报
217
613
  if (!this.apiConfig.enableErrorReport || !this.tracker) {
218
614
  return;
219
615
  }
220
- this.tracker.trackError({
221
- err: err,
222
- apptype: '10003',
223
- ...extra
224
- });
225
- }
616
+ try {
617
+ // 附加用户信息
618
+ var user = JSON.parse(window.localStorage.user || '{}');
619
+ var uid = user.uid || '';
620
+ if (uid) {
621
+ extra = extra || {};
622
+ extra.uid = uid;
623
+ }
624
+ }
625
+ catch (e) {
626
+ console.error(e);
627
+ }
628
+ this.tracker.trackError(__assign({ err: err, apptype: '10003' }, extra));
629
+ };
226
630
  /**
227
631
  * 判断文件是否为图片(支持常见图片格式)
228
632
  * @param {File} file - 上传的File对象
229
633
  * @returns {boolean} 是否为图片
230
634
  */
231
- isImageFile(file) {
635
+ AliOssClass.prototype.isImageFile = function (file) {
636
+ var _a;
232
637
  if (!file || !(file instanceof File))
233
638
  return false;
234
639
  // 1. 校验文件MIME类型(优先,更可靠)
235
640
  if (SUPPORTED_IMAGE_TYPES.includes(file.type))
236
641
  return true;
237
642
  // 2. 校验文件后缀名(兜底,防止MIME类型缺失)
238
- const fileExt = file.name.split('.').pop()?.toLowerCase() || '';
643
+ var fileExt = ((_a = file.name.split('.').pop()) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || '';
239
644
  return SUPPORTED_IMAGE_EXTS.includes(fileExt);
240
- }
645
+ };
241
646
  /**
242
647
  * 通过V4签名上传
243
648
  * @param file 上传的文件
@@ -247,413 +652,182 @@ export class AliOssClass {
247
652
  * @param reject Promse
248
653
  * @returns 上传图片结果
249
654
  */
250
- async upload(params) {
251
- const { file, businessType, resolve, reject, callbacks } = params;
252
- let { size } = params;
253
- let result = {};
254
- try {
255
- let docType = file.name?.split('.').reverse()[0] || file.type; // 兼容 *.*.* 这种后缀(必传)
256
- if (!size && this.isImageFile(file)) {
257
- const image = await this.getImageInfo(file);
258
- size = `_${image?.width}_${image?.height}`;
259
- docType = file.type?.split('/').reverse()[0] || file.type; // 如果是图片文件格式如png(必传)
260
- }
261
- // 步骤 1:请求后端获取所有签名字段
262
- const signResponse = await this.apiConfig.getSts({
263
- businessType: businessType,
264
- docType,
265
- size: size, // _1024_567(可选)
266
- });
267
- if (signResponse.data.code !== 0) {
268
- const errorMessage = `获取签名失败:${signResponse.data.message || signResponse.data.msg}`;
269
- callbacks?.onError(errorMessage);
270
- reject && reject(errorMessage);
271
- console.error(errorMessage);
272
- this.reportError(errorMessage, { type: 'getSts', businessType, code: signResponse.data.code });
273
- return result;
274
- }
275
- const signData = await signResponse.data.data;
276
- // console.log('后端返回的签名字段:', signData)
277
- // 步骤 2:构造 FormData(字段名必须和后端返回一致
278
- const formData = new FormData();
279
- // formData.append('autherid', signData['autherid'])
280
- // formData.append('uid', signData['uid'])
281
- formData.append('key', signData['key']);
282
- formData.append('policy', signData['policy']);
283
- formData.append('success_action_status', '200');
284
- formData.append('x-oss-credential', signData['credential']);
285
- formData.append('x-oss-date', signData['date']);
286
- if (signData['securityToken']) {
287
- formData.append('x-oss-security-token', signData['securityToken']);
288
- }
289
- formData.append('x-oss-signature', signData['signature']);
290
- formData.append('x-oss-signature-version', signData['signatureVersion']);
291
- formData.append('file', file);
292
- // 步骤 3:发送 POST 请求到 OSS
293
- const uploadResponse = await fetch(signData.uploadUrl, {
294
- method: 'POST',
295
- body: formData,
296
- // 重点:不要手动设置 Content-Type!浏览器会自动处理为 multipart/form-data 并带边界符
297
- headers: { Accept: '*/*' },
655
+ AliOssClass.prototype.upload = function (params) {
656
+ var _a, _b;
657
+ return __awaiter(this, void 0, void 0, function () {
658
+ var file, businessType, resolve, reject, callbacks, size, result, docType, image, signResponse, errorMessage, signData, formData, uploadResponse, responseText, errorMessage, err_1, errMsg;
659
+ return __generator(this, function (_c) {
660
+ switch (_c.label) {
661
+ case 0:
662
+ file = params.file, businessType = params.businessType, resolve = params.resolve, reject = params.reject, callbacks = params.callbacks;
663
+ size = params.size;
664
+ result = {};
665
+ _c.label = 1;
666
+ case 1:
667
+ _c.trys.push([1, 8, , 9]);
668
+ docType = ((_a = file.name) === null || _a === void 0 ? void 0 : _a.split('.').reverse()[0]) || file.type // 兼容 *.*.* 这种后缀(必传)
669
+ ;
670
+ if (!(!size && this.isImageFile(file))) return [3 /*break*/, 3];
671
+ return [4 /*yield*/, this.getImageInfo(file)];
672
+ case 2:
673
+ image = _c.sent();
674
+ size = "_".concat(image === null || image === void 0 ? void 0 : image.width, "_").concat(image === null || image === void 0 ? void 0 : image.height);
675
+ docType = ((_b = file.type) === null || _b === void 0 ? void 0 : _b.split('/').reverse()[0]) || file.type; // 如果是图片文件格式如png(必传)
676
+ _c.label = 3;
677
+ case 3: return [4 /*yield*/, this.apiConfig.getSts({
678
+ businessType: businessType,
679
+ docType: docType,
680
+ size: size, // _1024_567(可选)
681
+ })];
682
+ case 4:
683
+ signResponse = _c.sent();
684
+ if (signResponse.data.code !== 0) {
685
+ errorMessage = "\u83B7\u53D6\u7B7E\u540D\u5931\u8D25\uFF1A".concat(signResponse.data.message || signResponse.data.msg);
686
+ callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError(errorMessage);
687
+ reject && reject(errorMessage);
688
+ console.error(errorMessage);
689
+ this.reportError(errorMessage, { type: 'getSts', businessType: businessType, code: signResponse.data.code });
690
+ return [2 /*return*/, result];
691
+ }
692
+ return [4 /*yield*/, signResponse.data.data
693
+ // console.log('后端返回的签名字段:', signData)
694
+ // 步骤 2:构造 FormData(字段名必须和后端返回一致
695
+ ];
696
+ case 5:
697
+ signData = _c.sent();
698
+ formData = new FormData();
699
+ // formData.append('autherid', signData['autherid'])
700
+ // formData.append('uid', signData['uid'])
701
+ formData.append('key', signData['key']);
702
+ formData.append('policy', signData['policy']);
703
+ formData.append('success_action_status', '200');
704
+ formData.append('x-oss-credential', signData['credential']);
705
+ formData.append('x-oss-date', signData['date']);
706
+ if (signData['securityToken']) {
707
+ formData.append('x-oss-security-token', signData['securityToken']);
708
+ }
709
+ formData.append('x-oss-signature', signData['signature']);
710
+ formData.append('x-oss-signature-version', signData['signatureVersion']);
711
+ formData.append('file', file);
712
+ return [4 /*yield*/, fetch(signData.uploadUrl, {
713
+ method: 'POST',
714
+ body: formData,
715
+ // 重点:不要手动设置 Content-Type!浏览器会自动处理为 multipart/form-data 并带边界符
716
+ headers: { Accept: '*/*' },
717
+ })
718
+ // 步骤 4:处理上传结果
719
+ ];
720
+ case 6:
721
+ uploadResponse = _c.sent();
722
+ return [4 /*yield*/, uploadResponse.text()];
723
+ case 7:
724
+ responseText = _c.sent();
725
+ if (uploadResponse.ok) {
726
+ result = {
727
+ url: signData['fileUrl'],
728
+ imgUrl: signData['fileUrl'],
729
+ imgOrgUrl: signData['fileUrl'],
730
+ name: file.name,
731
+ fileName: file.name,
732
+ };
733
+ callbacks === null || callbacks === void 0 ? void 0 : callbacks.onSuccess(result);
734
+ resolve && resolve(result);
735
+ }
736
+ else {
737
+ errorMessage = "\u4E0A\u4F20\u5931\u8D25\uFF08OSS \u8FD4\u56DE ".concat(uploadResponse.status, "\uFF09\uFF1A").concat(responseText);
738
+ callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError(errorMessage);
739
+ reject && reject(errorMessage);
740
+ console.error(errorMessage);
741
+ this.reportError(errorMessage, { type: 'ossUpload', businessType: businessType, status: uploadResponse.status });
742
+ }
743
+ return [3 /*break*/, 9];
744
+ case 8:
745
+ err_1 = _c.sent();
746
+ errMsg = err_1.message || err_1.msg || '上传异常';
747
+ callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError(errMsg);
748
+ reject && reject(errMsg);
749
+ console.error('上传异常:', errMsg);
750
+ this.reportError(errMsg, { type: 'ossUploadException', businessType: businessType });
751
+ return [3 /*break*/, 9];
752
+ case 9: return [2 /*return*/, result];
753
+ }
298
754
  });
299
- // 步骤 4:处理上传结果
300
- const responseText = await uploadResponse.text();
301
- if (uploadResponse.ok) {
302
- result = {
303
- url: signData['fileUrl'],
304
- imgUrl: signData['fileUrl'],
305
- imgOrgUrl: signData['fileUrl'],
306
- name: file.name,
307
- fileName: file.name,
308
- };
309
- callbacks?.onSuccess(result);
310
- resolve && resolve(result);
311
- }
312
- else {
313
- const errorMessage = `上传失败(OSS 返回 ${uploadResponse.status}):${responseText}`;
314
- callbacks?.onError(errorMessage);
315
- reject && reject(errorMessage);
316
- console.error(errorMessage);
317
- this.reportError(errorMessage, { type: 'ossUpload', businessType, status: uploadResponse.status });
318
- }
319
- }
320
- catch (err) {
321
- const errMsg = err.message || err.msg || '上传异常';
322
- callbacks?.onError(errMsg);
323
- reject && reject(errMsg);
324
- console.error('上传异常:', errMsg);
325
- this.reportError(errMsg, { type: 'ossUploadException', businessType });
326
- }
327
- return result;
328
- }
755
+ });
756
+ };
329
757
  /**
330
758
  * 预加载图片获取尺寸
331
759
  * @param file 文件对象
332
760
  * @returns 图片对象
333
761
  */
334
- getImageInfo(file) {
335
- return new Promise((resolve, reject) => {
336
- const URL = window.URL || window.webkitURL;
337
- const image = new Image();
338
- const objectUrl = URL.createObjectURL(file);
339
- image.onload = () => {
762
+ AliOssClass.prototype.getImageInfo = function (file) {
763
+ return new Promise(function (resolve, reject) {
764
+ var URL = window.URL || window.webkitURL;
765
+ var image = new Image();
766
+ var objectUrl = URL.createObjectURL(file);
767
+ image.onload = function () {
340
768
  URL.revokeObjectURL(objectUrl); // 释放内存
341
769
  resolve(image);
342
770
  };
343
- image.onerror = () => {
771
+ image.onerror = function () {
344
772
  URL.revokeObjectURL(objectUrl); // 释放内存
345
773
  reject(new Error('图片加载失败'));
346
774
  };
347
775
  image.src = objectUrl;
348
776
  });
349
- }
777
+ };
350
778
  /**
351
779
  * 检查图片是否为长图
352
780
  * @param File 图片
353
781
  * @returns 是否为长图
354
782
  */
355
- async isLongImage(file) {
356
- // 预加载图片获取尺寸
357
- const image = await this.getImageInfo(file);
358
- const { width, height } = image;
359
- const maxDimension = Math.max(width, height);
360
- const minDimension = Math.min(width, height);
361
- return maxDimension / minDimension > LONG_IMAGE_RATIO;
362
- }
783
+ AliOssClass.prototype.isLongImage = function (file) {
784
+ return __awaiter(this, void 0, void 0, function () {
785
+ var image, width, height, maxDimension, minDimension;
786
+ return __generator(this, function (_a) {
787
+ switch (_a.label) {
788
+ case 0: return [4 /*yield*/, this.getImageInfo(file)];
789
+ case 1:
790
+ image = _a.sent();
791
+ width = image.width, height = image.height;
792
+ maxDimension = Math.max(width, height);
793
+ minDimension = Math.min(width, height);
794
+ return [2 /*return*/, maxDimension / minDimension > LONG_IMAGE_RATIO];
795
+ }
796
+ });
797
+ });
798
+ };
363
799
  /**
364
800
  * 加载图片并返回结果
365
801
  * 用于标准的图片上传场景
366
802
  * @param params 加载参数
367
803
  */
368
- loadImage(params) {
369
- const { url, val, file, option, resolve, reject } = params;
370
- let img = new Image();
804
+ AliOssClass.prototype.loadImage = function (params) {
805
+ var url = params.url, val = params.val, file = params.file, option = params.option, resolve = params.resolve, reject = params.reject;
806
+ var img = new Image();
371
807
  img.src = url;
372
808
  img.onload = function () {
809
+ var _a;
373
810
  if (!img)
374
811
  return;
375
- val.imgOrgUrl = `${url}?_${img.width}_${img.height}`;
812
+ val.imgOrgUrl = "".concat(url, "?_").concat(img.width, "_").concat(img.height);
376
813
  val.imgUrl = val.imgOrgUrl;
377
814
  val.name = file.name;
378
815
  val.fileName = file.name;
379
- option.onSuccess?.(val);
816
+ (_a = option.onSuccess) === null || _a === void 0 ? void 0 : _a.call(option, val);
380
817
  resolve(val);
381
818
  img = null;
382
819
  };
383
820
  img.onerror = function () {
384
- option.onError?.('图片加载失败');
821
+ var _a;
822
+ (_a = option.onError) === null || _a === void 0 ? void 0 : _a.call(option, '图片加载失败');
385
823
  reject('图片加载失败');
386
824
  img = null;
387
825
  };
388
- }
389
- /**
390
- * 图片上传主方法
391
- * 整合了所有项目的图片上传逻辑
392
- * @param option 上传选项
393
- * @returns Promise
394
- */
395
- ossUploadImage = async (option) => {
396
- if (!(option.file instanceof File)) {
397
- return Promise.reject('file is not instanceof File');
398
- }
399
- if (!option.businessType) {
400
- return Promise.reject('businessType不能为空');
401
- }
402
- const file = option.file;
403
- // 初始化回调函数
404
- const callbacks = {
405
- onError: option.onError || (() => { }),
406
- onSuccess: option.onSuccess || (() => { }),
407
- onProgress: option.onProgress || (() => { }),
408
- };
409
- option.onError = callbacks.onError;
410
- option.onSuccess = callbacks.onSuccess;
411
- option.onProgress = callbacks.onProgress;
412
- // 文件类型验证
413
- if (!isSupportedImageType(file.type)) {
414
- callbacks.onError('');
415
- this.apiConfig.messageWarning?.('上传失败,请上传后缀为png、gif、jpg的文件');
416
- return Promise.reject('文件类型不支持');
417
- }
418
- return new Promise(async (resolve, reject) => {
419
- try {
420
- // 注释:小图片(≤100KB)不压缩,quality设为1 (MAIN-2481)
421
- const isSmallImage = getFileSizeInKB(file.size) <= SMALL_IMAGE_THRESHOLD;
422
- let quality = isSmallImage ? 1 : option.quality || DEFAULT_QUALITY;
423
- const businessType = option.businessType;
424
- if (businessType === BusinessType.CREDIT) {
425
- return await this.upload({
426
- file,
427
- businessType,
428
- resolve,
429
- reject,
430
- callbacks,
431
- });
432
- }
433
- // 注释:batchTransfer选项 - 批量转换水印(用于某些特殊业务场景)
434
- if (option.batchTransfer && this.apiConfig.multiTransferImage) {
435
- const res = await this.apiConfig.multiTransferImage({ file });
436
- if (res.data.code === 0) {
437
- // 盲水印兼容报错
438
- if (res.data.data) {
439
- this.loadImage({
440
- url: res.data.data,
441
- val: res.data,
442
- option,
443
- file,
444
- resolve,
445
- reject,
446
- });
447
- }
448
- }
449
- else {
450
- callbacks.onError('上传失败');
451
- reject('上传失败');
452
- this.reportError('批量转换水印上传失败', { type: 'batchTransfer', businessType });
453
- }
454
- return;
455
- }
456
- // 注释:carport类型需要打暗水印
457
- if (option.imageType === 'carport' &&
458
- this.apiConfig.darkWaterUploadImage) {
459
- const res = await this.apiConfig.darkWaterUploadImage({ file });
460
- if (res.data.code === 0) {
461
- this.loadImage({
462
- url: res.data.data,
463
- val: res.data,
464
- option,
465
- file,
466
- resolve,
467
- reject,
468
- });
469
- }
470
- else {
471
- callbacks.onError('上传失败');
472
- reject('上传失败');
473
- this.reportError('暗水印上传失败', { type: 'darkWater', businessType });
474
- }
475
- return;
476
- }
477
- // 图片压缩
478
- const rst = await lrz(file, { quality });
479
- // 注释:长图压缩有问题,长宽比>2:1的图片不压缩
480
- const isLong = (await this.isLongImage(file)) || false;
481
- // 确定最终上传的文件
482
- let postFile;
483
- if (option.notCompress || file.type === 'image/gif' || isLong) {
484
- // 注释:GIF、notCompress选项或长图不压缩
485
- postFile = file;
486
- }
487
- else {
488
- postFile = rst.file;
489
- }
490
- // 文件大小验证
491
- const imgSize = postFile.size;
492
- const maxSizeMB = DEFAULT_FILE_SIZE_LIMIT;
493
- if (getFileSizeInMB(imgSize) > maxSizeMB) {
494
- const errorMsg = `图片不能超过${maxSizeMB}M`;
495
- callbacks.onError(errorMsg);
496
- reject(errorMsg);
497
- return;
498
- }
499
- // 设置文件名(确保压缩后的文件有名称)
500
- if (!postFile.name) {
501
- Object.defineProperty(postFile, 'name', {
502
- value: file.name,
503
- writable: false,
504
- });
505
- }
506
- const result = await this.upload({
507
- file,
508
- businessType,
509
- resolve,
510
- reject,
511
- callbacks,
512
- });
513
- // 注释:idCard场景 - 生成预签名URL
514
- if ((option.idCard || false) &&
515
- this.apiConfig.generatePrePresignedUrl) {
516
- const res = await this.apiConfig.generatePrePresignedUrl({
517
- objectId: result.name,
518
- expireMils: PRESIGNED_URL_EXPIRE_TIME,
519
- });
520
- if (res.data.code === 0) {
521
- this.loadImage({
522
- url: res.data.data,
523
- val: result,
524
- file: postFile,
525
- option,
526
- resolve,
527
- reject,
528
- });
529
- }
530
- else {
531
- callbacks.onError('生成预签名URL失败');
532
- reject('生成预签名URL失败');
533
- this.reportError('生成预签名URL失败', { type: 'preSignedUrl', businessType });
534
- }
535
- return;
536
- }
537
- }
538
- catch (error) {
539
- const errorMsg = error.message || error.msg || '上传异常';
540
- callbacks.onError(errorMsg);
541
- reject(errorMsg);
542
- this.reportError(errorMsg, { type: 'ossUploadImage', businessType: option.businessType });
543
- }
544
- });
545
- };
546
- /**
547
- * 文件上传方法
548
- * 支持视频、文档、APK等文件类型
549
- * @param option 上传选项
550
- * @returns Promise
551
- */
552
- ossUploadFile = async (option) => {
553
- if (!(option.file instanceof File)) {
554
- return Promise.reject('file is not instanceof File');
555
- }
556
- if (!option.businessType) {
557
- return Promise.reject('businessType不能为空');
558
- }
559
- const file = option.file;
560
- // 初始化回调函数
561
- const callbacks = {
562
- onError: option.onError || (() => { }),
563
- onSuccess: option.onSuccess || (() => { }),
564
- onProgress: option.onProgress || (() => { }),
565
- };
566
- option.onError = callbacks.onError;
567
- option.onSuccess = callbacks.onSuccess;
568
- option.onProgress = callbacks.onProgress;
569
- return new Promise(async (resolve, reject) => {
570
- try {
571
- let businessType = option.businessType;
572
- await this.upload({
573
- file,
574
- businessType,
575
- resolve,
576
- reject,
577
- callbacks,
578
- });
579
- }
580
- catch (error) {
581
- const errorMsg = error.message || error.msg || '上传异常';
582
- callbacks.onError(errorMsg);
583
- reject(errorMsg);
584
- this.reportError(errorMsg, { type: 'ossUploadFile', businessType: option.businessType });
585
- }
586
- });
587
826
  };
588
- /**
589
- * 纯图片上传 pureOssUploadImage
590
- * 注释:图片上传,不压缩
591
- * @param option 上传选项
592
- * @returns Promise
593
- */
594
- pureOssUploadImage = async (option) => {
595
- return await this.shopDetailUpdate(option);
596
- };
597
- /**
598
- * 商品详情图片上传(不建议直接使用,请使用 pureOssUploadImage)
599
- * 注释:图片上传,不压缩
600
- * @param option 上传选项
601
- * @returns Promise
602
- */
603
- shopDetailUpdate = async (option) => {
604
- if (!(option.file instanceof File)) {
605
- return Promise.reject('file is not instanceof File');
606
- }
607
- if (!option.businessType) {
608
- return Promise.reject('businessType不能为空');
609
- }
610
- const file = option.file;
611
- // 初始化回调函数
612
- const callbacks = {
613
- onError: option.onError || (() => { }),
614
- onSuccess: option.onSuccess || (() => { }),
615
- onProgress: option.onProgress || (() => { }),
616
- };
617
- option.onError = callbacks.onError;
618
- option.onSuccess = callbacks.onSuccess;
619
- option.onProgress = callbacks.onProgress;
620
- // 文件类型验证
621
- if (!isSupportedImageType(file.type)) {
622
- callbacks.onError('');
623
- this.apiConfig.messageWarning?.('上传失败,请上传后缀为png、gif、jpg的文件');
624
- return Promise.reject('文件类型不支持');
625
- }
626
- return new Promise(async (resolve, reject) => {
627
- try {
628
- const businessType = option.businessType;
629
- // 文件大小验证
630
- if (getFileSizeInMB(file.size) > DEFAULT_FILE_SIZE_LIMIT) {
631
- const errorMsg = `图片不能超过${DEFAULT_FILE_SIZE_LIMIT}M`;
632
- callbacks.onError(errorMsg);
633
- reject(errorMsg);
634
- return;
635
- }
636
- await this.upload({
637
- file,
638
- businessType,
639
- resolve,
640
- reject,
641
- callbacks,
642
- });
643
- }
644
- catch (error) {
645
- const errorMsg = error.message || error.msg || '上传异常';
646
- callbacks.onError(errorMsg);
647
- reject(errorMsg);
648
- this.reportError(errorMsg, { type: 'pureOssUploadImage', businessType: option.businessType });
649
- }
650
- });
651
- };
652
- /**
653
- * 业务类型枚举
654
- */
655
- businessType = BusinessType;
656
- }
827
+ AliOssClass.instance = null;
828
+ return AliOssClass;
829
+ }());
830
+ export { AliOssClass };
657
831
  /**
658
832
  * 创建阿里云OSS上传器(工厂函数,内部已实现单例)
659
833
  * @param apiConfig API配置对象,包含业务相关的API函数
@@ -666,6 +840,6 @@ export function createAliOssUploader(apiConfig) {
666
840
  * 默认导出
667
841
  */
668
842
  export default {
669
- createAliOssUploader,
670
- BusinessType,
843
+ createAliOssUploader: createAliOssUploader,
844
+ BusinessType: BusinessType,
671
845
  };