sadais-piui 1.2.7-beta15 → 1.2.7-beta151

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.
Files changed (75) hide show
  1. package/.prettierrc +8 -0
  2. package/components/pi-action-sheet/index.vue +260 -247
  3. package/components/pi-badge/index.vue +11 -1
  4. package/components/pi-bottom-bar/index.vue +1 -1
  5. package/components/pi-calendar/index.vue +207 -182
  6. package/components/pi-calendar-input/index.vue +61 -30
  7. package/components/pi-calendar-panel/components/calendar-days/index.vue +91 -52
  8. package/components/pi-calendar-panel/index.vue +28 -12
  9. package/components/pi-canvas/index.vue +8 -1
  10. package/components/pi-cascader/index.vue +601 -0
  11. package/components/pi-checkbox/index.vue +8 -4
  12. package/components/pi-checkbox-group/index.vue +12 -11
  13. package/components/pi-circle-progress/index.vue +53 -16
  14. package/components/pi-code-input/index.vue +11 -3
  15. package/components/pi-collapse/index.vue +16 -6
  16. package/components/pi-collapse-item/index.vue +35 -22
  17. package/components/pi-date-picker/index.vue +512 -391
  18. package/components/pi-date-picker-input/index.vue +61 -30
  19. package/components/pi-dropdown/components/dropdown-tab.vue +33 -23
  20. package/components/pi-dropdown/index.vue +34 -19
  21. package/components/pi-dropdown-item/index.vue +70 -58
  22. package/components/pi-form-item/index.vue +98 -20
  23. package/components/pi-grid/index.vue +1 -1
  24. package/components/pi-grid-item/index.vue +4 -4
  25. package/components/pi-img/index.vue +275 -267
  26. package/components/pi-img-cropper/index.vue +6 -3
  27. package/components/pi-input/index.vue +97 -36
  28. package/components/pi-list-item/index.vue +1 -1
  29. package/components/pi-marquee/index.vue +322 -310
  30. package/components/pi-marquee-pure-css/index.vue +267 -0
  31. package/components/pi-mask/index.vue +3 -1
  32. package/components/pi-modal/index.vue +311 -303
  33. package/components/pi-pagination/index.vue +13 -0
  34. package/components/pi-picker/index.vue +332 -317
  35. package/components/pi-popup/index.vue +4 -1
  36. package/components/pi-popup-select/index.vue +13 -4
  37. package/components/pi-radio/index.vue +12 -11
  38. package/components/pi-radio-group/index.vue +25 -5
  39. package/components/pi-regions-select/index.vue +6 -1
  40. package/components/pi-regions-select-input/index.vue +69 -31
  41. package/components/pi-search/index.vue +37 -2
  42. package/components/pi-section/index.vue +1 -1
  43. package/components/pi-select/index.vue +237 -22
  44. package/components/pi-select-input/index.vue +106 -41
  45. package/components/pi-stepper/index.vue +135 -121
  46. package/components/pi-steps/index.vue +115 -36
  47. package/components/pi-swiper/index.vue +22 -7
  48. package/components/pi-switch/index.vue +5 -1
  49. package/components/pi-table/index.vue +351 -0
  50. package/components/pi-tabs/index.vue +46 -10
  51. package/components/pi-upload-img/index.vue +895 -44
  52. package/components/pi-webview/index.vue +95 -82
  53. package/config/actionSheet.js +0 -1
  54. package/config/calendarInput.js +2 -1
  55. package/config/calendarPanel.js +2 -1
  56. package/config/cascader.js +22 -0
  57. package/config/circleProgress.js +12 -4
  58. package/config/codeInput.js +2 -1
  59. package/config/datePicker.js +29 -24
  60. package/config/datePickerInput.js +2 -1
  61. package/config/dropdown.js +3 -1
  62. package/config/input.js +5 -3
  63. package/config/marqueePureCss.js +18 -0
  64. package/config/regionsSelectInput.js +2 -1
  65. package/config/select.js +13 -1
  66. package/config/selectInput.js +2 -1
  67. package/config/steps.js +1 -1
  68. package/config/table.js +9 -0
  69. package/config/uploadImg.js +33 -11
  70. package/mixin/emitter.js +8 -1
  71. package/mixin/value-sync.js +5 -0
  72. package/package.json +5 -2
  73. package/scss/common.scss +11 -14
  74. package/scss/icon/icon.scss +2 -1
  75. package/scss/mixin.scss +5 -5
@@ -1,34 +1,82 @@
1
1
  <!--
2
2
  * @Author: zhangzhenfei
3
3
  * @Date: 2021-08-13 11:31:57
4
- * @LastEditTime: 2022-04-12 09:11:41
4
+ * @LastEditTime: 2025-04-18 16:28:01
5
5
  * @LastEditors: zhangzhenfei
6
6
  * @Description: 图片上传组件
7
- * @FilePath: \hfmp-checkin-frontc:\Users\feilin\workspace\sadais\piui-awesome\src\piui\components\pi-upload-img\index.vue
7
+ * @FilePath: \piui\components\pi-upload-img\index.vue
8
8
  -->
9
9
 
10
10
  <template>
11
- <view class="pi-upload-img" :style="[customStyle]" :class="[customClass]">
11
+ <view
12
+ class="pi-upload-img"
13
+ :style="[customStyle]"
14
+ :class="[customClass, { 'pi-pd-top-12': !getDisabled }]"
15
+ >
12
16
  <!-- 已上传图片展示 -->
13
17
  <view
14
18
  v-for="(img, index) in getImgs"
15
19
  :key="index"
16
20
  class="pi-rela pi-flex-column-center"
17
- @tap="handlePreviewImage(img)"
21
+ @tap="handlePreview(img)"
18
22
  >
19
- <view class="close" @tap.stop="handleDelete(index)">
23
+ <view v-if="!getDisabled" class="close" @tap.stop="handleDelete(index)">
20
24
  <pi-icon name="roundclosefill" color="#8e8e8e" size="36" />
21
25
  </view>
22
26
  <image
27
+ v-if="isImageFilename(imgField ? img[imgField] : img)"
23
28
  :style="[getItemStyle]"
24
29
  class="pi-of-hidden"
25
30
  :mode="imageMode"
26
31
  :src="imgField ? img[imgField] : img"
27
32
  />
33
+ <view
34
+ v-else
35
+ class="pi-rela pi-of-hidden pi-radius-8"
36
+ :style="[getItemStyle]"
37
+ >
38
+ <view
39
+ class="file-mask"
40
+ :class="[
41
+ {
42
+ 'no-bg': fileIconMap[getFileType(imgField ? img[imgField] : img)]
43
+ }
44
+ ]"
45
+ >
46
+ <image
47
+ v-if="fileIconMap[getFileType(imgField ? img[imgField] : img)]"
48
+ :src="fileIconMap[getFileType(imgField ? img[imgField] : img)]"
49
+ mode="widthFix"
50
+ style="width: 100%"
51
+ />
52
+ <template v-else>
53
+ <pi-icon
54
+ :name="
55
+ isVideoFilename(imgField ? img[imgField] : img)
56
+ ? 'videofill'
57
+ : 'activity-fill'
58
+ "
59
+ size="48"
60
+ color="#0C6DF4"
61
+ />
62
+ <view class="pi-mg-top-12 pi-fz-22">
63
+ {{ getFileType(imgField ? img[imgField] : img) }}
64
+ </view>
65
+ </template>
66
+ </view>
67
+ </view>
28
68
  </view>
29
69
  <!-- 上传框 -->
30
- <view v-if="getUploadMaxCount">
31
- <view :style="[getUploadBtnStyle]" class="pi-flex-column-center" @tap="handleChooseImage">
70
+ <view
71
+ v-if="
72
+ getUploadMaxCount && (!getDisabled || (getDisabled && !getImgs.length))
73
+ "
74
+ >
75
+ <view
76
+ :style="[getUploadBtnStyle]"
77
+ class="pi-flex-column-center"
78
+ @tap="handleChoose"
79
+ >
32
80
  <slot name="uploadBtn">
33
81
  <!-- 添加按钮 -->
34
82
  <pi-icon
@@ -43,11 +91,17 @@
43
91
  :class-prefix="getUploadIcon.classPrefix"
44
92
  />
45
93
  </slot>
46
- <view v-if="uploadText" class="pi-mg-top-6 pi-fz-24 pi-light-gray">{{ uploadText }}</view>
94
+ <view v-if="uploadText" class="pi-mg-top-6 pi-fz-24 pi-light-gray">{{
95
+ uploadText
96
+ }}</view>
47
97
  </view>
48
98
  </view>
49
99
  <!-- 剪裁弹窗 -->
50
- <pi-mask v-model="showCrop" :mask-closeable="false" background="rgba(0, 0, 0, .9)">
100
+ <pi-mask
101
+ v-model="showCrop"
102
+ :mask-closeable="false"
103
+ background="rgba(0, 0, 0, .9)"
104
+ >
51
105
  <view class="pi-abso-full pi-flex-column">
52
106
  <view class="pi-flex-sub">
53
107
  <pi-img-cropper
@@ -71,13 +125,44 @@
71
125
  :background="getCropMaskBackground"
72
126
  :safe-area-bg-color="getCropMaskBackground"
73
127
  >
74
- <view class="pi-justify-between pi-align-center pi-pd-tb-32 pi-pd-lr-24 pi-fz-32">
128
+ <view
129
+ class="pi-justify-between pi-align-center pi-pd-tb-32 pi-pd-lr-24 pi-fz-32"
130
+ >
75
131
  <view class="pi-white" @tap="handleCancelCrop">取消</view>
76
132
  <view class="pi-primary" @tap="handleCompelteCrop">完成</view>
77
133
  </view>
78
134
  </pi-bottom-bar>
79
135
  </view>
80
136
  </pi-mask>
137
+ <!-- 上传视频操作面板(小程序专用) -->
138
+ <pi-action-sheet
139
+ v-model="showActionSheet"
140
+ :items="actionSheetItems"
141
+ :popup="{
142
+ borderRadius: 0
143
+ }"
144
+ @select="handleActionSheetSelect"
145
+ />
146
+
147
+ <!-- 自定义拍照操作面板(小程序专用) -->
148
+ <pi-select
149
+ v-model="showCustomTakePhoto"
150
+ :items="customTakePhotoItems"
151
+ :single-cancel="false"
152
+ single-confirm
153
+ :item-style="{
154
+ padding: '32rpx'
155
+ }"
156
+ :popup="{
157
+ borderRadius: 0
158
+ }"
159
+ :popup-select="{
160
+ showTitle: true,
161
+ title: '请选择拍摄方式'
162
+ }"
163
+ item-height="auto"
164
+ @confirm="handleCustomTakePhotoSelect"
165
+ />
81
166
  </view>
82
167
  </template>
83
168
 
@@ -94,6 +179,16 @@ const { uploadImg } = getConfig()
94
179
 
95
180
  const PI_DEFAULT_FN_FLAG = 'PI_DEFAULT_FN_FLAG'
96
181
 
182
+ function isImageFilename(filename) {
183
+ const imageExtensions = /\.(jpg|jpeg|png|gif|bmp|tiff|webp)$/i
184
+ return imageExtensions.test(filename) || filename.startsWith('data:')
185
+ }
186
+
187
+ function isVideoFilename(filename) {
188
+ const videoExtensions = /\.(mp4|avi|mov|wmv|mpg|flv|mkv)$/i
189
+ return videoExtensions.test(filename)
190
+ }
191
+
97
192
  export default {
98
193
  name: 'PiUploadImg',
99
194
  // 混入v-model
@@ -232,14 +327,7 @@ export default {
232
327
  return uploadImg.uploadIcon
233
328
  }
234
329
  },
235
- // 调用uniapp.chooseImageOpts参数
236
- chooseImageOpts: {
237
- type: Object,
238
- default() {
239
- return uploadImg.chooseImageOpts
240
- }
241
- },
242
- // 当maxCount设置为1的时候,可开启裁剪
330
+ // 当maxCount设置为1的时候,且type为‘image’,可开启裁剪
243
331
  crop: {
244
332
  type: Boolean,
245
333
  // `false`
@@ -291,38 +379,221 @@ export default {
291
379
  fn: uploadImg.beforeRemove
292
380
  }
293
381
  }
382
+ },
383
+ // 压缩参数
384
+ compressOption: {
385
+ type: Object,
386
+ default() {
387
+ return uploadImg.compressOption
388
+ }
389
+ },
390
+ // 文件类型
391
+ type: {
392
+ type: String,
393
+ default() {
394
+ return uploadImg.type // 'all', 'image', 'video'
395
+ }
396
+ },
397
+ // 当 type 为 all 时生效,允许上传的文件类型是否包含 video 和 image
398
+ fileTypes: {
399
+ type: Array,
400
+ default() {
401
+ return uploadImg.fileTypes
402
+ }
403
+ },
404
+ // 当type为 "all"时生效,调用uni.chooseFile参数
405
+ chooseFileOpts: {
406
+ type: Object,
407
+ default() {
408
+ return uploadImg.chooseFileOpts
409
+ }
410
+ },
411
+ // 当type为 "image"时生效,调用uni.chooseImage参数
412
+ chooseImageOpts: {
413
+ type: Object,
414
+ default() {
415
+ return uploadImg.chooseImageOpts
416
+ }
417
+ },
418
+ // 当type为 "video"时生效,调用uniapp.chooseVideo参数
419
+ chooseVideoOpts: {
420
+ type: Object,
421
+ default() {
422
+ return uploadImg.chooseVideoOpts
423
+ }
424
+ },
425
+ // 文件类型和图标映射关系,对象形式({PDF: 'https://xxx'})
426
+ fileIconMap: {
427
+ type: Object,
428
+ default() {
429
+ return uploadImg.fileIconMap
430
+ }
431
+ },
432
+ // 自定义上传参数,对象形式
433
+ customUploadParams: {
434
+ type: Object,
435
+ default() {
436
+ return uploadImg.customUploadParams
437
+ }
438
+ },
439
+ // 是否自定义拍照(如果为true,则不调用相机,通过事件自己实现拍照上传)
440
+ customTakePhoto: {
441
+ type: Boolean,
442
+ default() {
443
+ return uploadImg.customTakePhoto
444
+ }
445
+ },
446
+ // 文件大小限制,单位为字节,null表示不限制
447
+ fileLimit: {
448
+ type: [Number, String, null],
449
+ default() {
450
+ return uploadImg.fileLimit
451
+ }
294
452
  }
295
453
  },
296
454
  data() {
297
455
  return {
298
456
  showCrop: false, // 是否显示裁剪工具
299
457
  cropPic: '', // 需要剪裁的图片
300
- cropedPic: '' // 剪裁后的图片
458
+ cropedPic: '', // 剪裁后的图片
459
+ showActionSheet: false, // 是否显示上传视频操作面板
460
+ showCustomTakePhoto: false, // 是否显示自定义拍照操作面板
461
+ currentSourceType: ['camera', 'album'] // 当前选择的拍照方式
301
462
  }
302
463
  },
303
464
  computed: {
465
+ // 判断是否为企业微信
466
+ isQYWX() {
467
+ let isQYWX = false
468
+ // #ifdef H5
469
+ const ua = navigator.userAgent.toLowerCase()
470
+ isQYWX = ua.indexOf('wxwork') !== -1
471
+ // #endif
472
+ return isQYWX
473
+ },
474
+ getDisabled() {
475
+ const parent = this.$pi.parent(this, 'PiFormItem')
476
+ return this.disabled || (parent && parent.getDisabled)
477
+ },
478
+ actionSheetItems() {
479
+ return [
480
+ {
481
+ id: 1,
482
+ text: '选择媒体图片/视频'
483
+ },
484
+ {
485
+ id: 2,
486
+ text: '选择微信聊天文件'
487
+ }
488
+ ]
489
+ },
490
+ customTakePhotoItems() {
491
+ // currentSourceType 当前选择的拍照方式 ['camera', 'album']
492
+ let sourceType = this.currentSourceType || ['camera', 'album']
493
+ if (sourceType.length === 0) {
494
+ sourceType = ['camera', 'album']
495
+ }
496
+ const items = [
497
+ {
498
+ id: 'takePhoto',
499
+ text: '拍摄',
500
+ desc: '拍摄完成后上传图片(信号良好下使用)',
501
+ show: sourceType.includes('camera')
502
+ },
503
+ // {
504
+ // id: 'takePhotoOffline',
505
+ // text: '离线拍摄',
506
+ // desc: '拍摄完成后缓存到相册,待网络良好时上传(信号较差时使用)',
507
+ // show: sourceType.includes('camera')
508
+ // },
509
+ {
510
+ id: 'chooseFromAlbum',
511
+ text: '从手机相册选择',
512
+ show: sourceType.includes('album')
513
+ }
514
+ // {
515
+ // id: 'chooseFromCacheAlbum',
516
+ // text: '从缓存相册选择',
517
+ // show: true
518
+ // }
519
+ ]
520
+ return items.filter(item => item.show)
521
+ },
522
+ selectOnlyFile() {
523
+ return this.type === 'all' && this.fileTypes.length === 0
524
+ },
304
525
  isValString() {
305
526
  return this.$pi.lang.isString(this.val)
306
527
  },
307
528
  getImgs() {
308
- return this.isValString ? (this.val ? [this.val] : []) : this.val.filter(img => img)
529
+ if (this.val === null || this.val === undefined) {
530
+ return []
531
+ }
532
+ return this.isValString
533
+ ? this.val
534
+ ? [this.val]
535
+ : []
536
+ : this.val.filter(img => img)
309
537
  },
310
538
  getItemStyle() {
311
- return this.$pi.lang.mergeDeep(uploadImg.itemStyle, this.itemStyle)
539
+ const style = {
540
+ width: this.getSize,
541
+ height: this.getSize
542
+ }
543
+ const uploadStyle = this.$pi.lang.mergeDeep(
544
+ uploadImg.itemStyle,
545
+ this.itemStyle
546
+ )
547
+ return this.$pi.lang.mergeDeep(style, uploadStyle)
548
+ },
549
+ getSize() {
550
+ return this.$pi.common.addUnit(this.size)
312
551
  },
313
552
  getUploadBtnStyle() {
314
- return this.$pi.lang.mergeDeep(uploadImg.uploadBtnStyle, this.uploadBtnStyle)
553
+ const style = {
554
+ width: this.getSize,
555
+ height: this.getSize
556
+ }
557
+ const uploadBtnStyle = this.$pi.lang.mergeDeep(
558
+ uploadImg.uploadBtnStyle,
559
+ this.uploadBtnStyle
560
+ )
561
+ return this.$pi.lang.mergeDeep(style, uploadBtnStyle)
315
562
  },
316
563
  getUploadIcon() {
317
564
  return this.$pi.lang.mergeDeep(uploadImg.uploadIcon, this.uploadIcon)
318
565
  },
319
566
  getChooseImageOpts() {
320
567
  // 以覆盖的方式合并数组
321
- return this.$pi.lang.mergeDeep(uploadImg.chooseImageOpts, this.chooseImageOpts, {
322
- arrayMerge: (target, source) => source
323
- })
568
+ return this.$pi.lang.mergeDeep(
569
+ uploadImg.chooseImageOpts,
570
+ this.chooseImageOpts,
571
+ {
572
+ arrayMerge: (_target, source) => source
573
+ }
574
+ )
575
+ },
576
+ getChooseFileOpts() {
577
+ return this.$pi.lang.mergeDeep(
578
+ uploadImg.chooseFileOpts,
579
+ this.chooseFileOpts,
580
+ {
581
+ arrayMerge: (_target, source) => source
582
+ }
583
+ )
584
+ },
585
+ getChooseVideoOpts() {
586
+ return this.$pi.lang.mergeDeep(
587
+ uploadImg.chooseVideoOpts,
588
+ this.chooseVideoOpts,
589
+ {
590
+ arrayMerge: (_target, source) => source
591
+ }
592
+ )
324
593
  },
325
594
  getUploadMaxCount() {
595
+ // 如果 maxCount 为 0 或者 undefined,则不限制上传数量
596
+ if (!this.maxCount) return 9
326
597
  const maxCount = parseInt(this.maxCount, 10)
327
598
  return maxCount - this.getImgs.length
328
599
  },
@@ -331,9 +602,54 @@ export default {
331
602
  },
332
603
  getCropOption() {
333
604
  return this.$pi.lang.mergeDeep(uploadImg.cropOption, this.cropOption)
605
+ },
606
+ getExtension() {
607
+ let extension = []
608
+ if (this.type === 'image') {
609
+ extension = this.getChooseImageOpts.extension || []
610
+ } else if (this.type === 'video') {
611
+ extension = this.getChooseVideoOpts.extension || []
612
+ } else {
613
+ // all
614
+ extension = [
615
+ ...this.getChooseFileOpts.extension,
616
+ ...(this.fileTypes.includes('image')
617
+ ? this.getChooseImageOpts.extension
618
+ : []),
619
+ ...(this.fileTypes.includes('video')
620
+ ? this.getChooseVideoOpts.extension
621
+ : [])
622
+ ]
623
+ }
624
+ return extension?.filter(ext => !!ext)
334
625
  }
335
626
  },
336
627
  methods: {
628
+ isImageFilename,
629
+ isVideoFilename,
630
+ getFileType(file) {
631
+ if (!file) return ''
632
+ const ext = file.split('.').pop()
633
+ return ext.toLocaleUpperCase()
634
+ },
635
+ isRightType(selectFile) {
636
+ const isRightType = this.getExtension.some(ext =>
637
+ selectFile.name.endsWith(ext)
638
+ )
639
+ console.log(
640
+ TAG,
641
+ '当前文件扩展名配置为:',
642
+ this.getExtension,
643
+ '当前选择文件:',
644
+ selectFile.name,
645
+ '是否符合:',
646
+ isRightType
647
+ )
648
+ if (!isRightType) {
649
+ this.$toast(`请选择${this.getExtension.join('/')}文件上传`)
650
+ }
651
+ return isRightType
652
+ },
337
653
  async handleDelete(index) {
338
654
  let val = null
339
655
  const beforeRemove = this.beforeRemove[PI_DEFAULT_FN_FLAG]
@@ -349,6 +665,43 @@ export default {
349
665
  this.val = val
350
666
  this.handleEmitChange()
351
667
  },
668
+ handlePreview(img) {
669
+ const file = this.imgField ? img[this.imgField] : img
670
+ if (isImageFilename(file)) {
671
+ this.handlePreviewImage(file)
672
+ return
673
+ }
674
+ if (isVideoFilename(file)) {
675
+ this.$emit('previewVideo', file)
676
+ return
677
+ }
678
+ // 文件预览
679
+ // 判断是企业微信
680
+ if (this.isQYWX) {
681
+ const form = document.createElement('form')
682
+ form.action = file
683
+ form.method = 'GET'
684
+ form.target = '_blank'
685
+ document.body.appendChild(form)
686
+ form.submit()
687
+ return
688
+ }
689
+ uni.downloadFile({
690
+ url: file,
691
+ success: res => {
692
+ const filePath = res.tempFilePath
693
+ // fileType 文件类型,指定文件类型打开文件,有效值 doc, xls, ppt, pdf, docx, xlsx, pptx,支付宝小程序仅支持pdf
694
+ // 支付宝小程序必填,其他平台非必填
695
+ uni.openDocument({
696
+ filePath,
697
+ showMenu: true, // 右上角是否有可以转发分享的功能
698
+ complete: res => {
699
+ console.log('文件预览', res)
700
+ }
701
+ })
702
+ }
703
+ })
704
+ },
352
705
  // 预览图片
353
706
  handlePreviewImage(img) {
354
707
  if (!this.previewFullImage) return
@@ -359,10 +712,15 @@ export default {
359
712
  current = this.val
360
713
  urls = [this.val]
361
714
  } else {
362
- urls = this.imgField ? this.val.map(img => img[this.imgField]) : this.val
363
- current = this.imgField ? img[this.imgField] : img
715
+ urls = this.imgField
716
+ ? this.val.map(img => img[this.imgField])
717
+ : this.val
718
+ current = img
364
719
  }
365
720
 
721
+ // 过滤出图片类型的文件
722
+ urls = urls.filter(url => isImageFilename(url))
723
+
366
724
  // eslint-disable-next-line no-undef
367
725
  uni.previewImage({
368
726
  urls,
@@ -373,22 +731,157 @@ export default {
373
731
  }
374
732
  })
375
733
  },
734
+ // 检查文件大小限制
735
+ checkFileSize(files) {
736
+ if (!this.fileLimit) return { valid: true, files }
737
+
738
+ const limitBytes = this.parseFileSize(this.fileLimit)
739
+ const validFiles = []
740
+ const oversizedFiles = []
741
+
742
+ for (const file of files) {
743
+ // 对于不同的文件对象,获取文件大小的方式可能不同
744
+ let fileSize = 0
745
+ if (file && file.size !== undefined) {
746
+ // 标准的 File 对象或有 size 属性的对象
747
+ fileSize = file.size
748
+ } else if (file && file.tempFile && file.tempFile.size !== undefined) {
749
+ // uni-app 的 tempFile 格式
750
+ fileSize = file.tempFile.size
751
+ } else if (typeof file === 'string') {
752
+ // 如果是纯路径字符串,无法获取文件大小,跳过检查
753
+ validFiles.push(file)
754
+ continue
755
+ } else {
756
+ // 如果无法获取文件大小,跳过检查
757
+ validFiles.push(file)
758
+ continue
759
+ }
760
+
761
+ if (fileSize > limitBytes) {
762
+ oversizedFiles.push({
763
+ file,
764
+ size: fileSize,
765
+ humanSize: this.formatFileSize(fileSize)
766
+ })
767
+ } else {
768
+ validFiles.push(file)
769
+ }
770
+ }
771
+
772
+ if (oversizedFiles.length > 0) {
773
+ const limitHumanSize = this.formatFileSize(limitBytes)
774
+ const message =
775
+ oversizedFiles.length === 1
776
+ ? `文件限制大小: ${limitHumanSize}`
777
+ : `有 ${oversizedFiles.length} 个文件限制: ${limitHumanSize}`
778
+
779
+ this.$toast(message)
780
+ return { valid: false, files: validFiles, oversizedFiles }
781
+ }
782
+
783
+ return { valid: true, files: validFiles }
784
+ },
785
+ // 解析文件大小字符串或数字为字节数
786
+ parseFileSize(size) {
787
+ if (typeof size === 'number') return size
788
+ if (typeof size === 'string') {
789
+ const units = {
790
+ B: 1,
791
+ KB: 1024,
792
+ MB: 1024 * 1024,
793
+ GB: 1024 * 1024 * 1024
794
+ }
795
+
796
+ const regex = /^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB)$/i
797
+ const match = size.trim().match(regex)
798
+
799
+ if (match) {
800
+ const value = parseFloat(match[1])
801
+ const unit = match[2].toUpperCase()
802
+ return value * units[unit]
803
+ }
804
+
805
+ // 如果没有单位,默认为字节
806
+ const numSize = parseInt(size, 10)
807
+ return isNaN(numSize) ? 0 : numSize
808
+ }
809
+ return 0
810
+ },
811
+ // 格式化文件大小显示
812
+ formatFileSize(bytes) {
813
+ if (bytes === 0) return '0 B'
814
+
815
+ const units = ['B', 'KB', 'MB', 'GB']
816
+ let size = bytes
817
+ let unitIndex = 0
818
+
819
+ while (size >= 1024 && unitIndex < units.length - 1) {
820
+ size /= 1024
821
+ unitIndex++
822
+ }
823
+
824
+ return `${size.toFixed(unitIndex === 0 ? 0 : 1)} ${units[unitIndex]}`
825
+ },
826
+ // 获取文件路径的文件信息(包含大小)
827
+ async getFileInfoForPaths(filePaths) {
828
+ const fileInfos = []
829
+
830
+ for (const filePath of filePaths) {
831
+ try {
832
+ // #ifdef APP-PLUS || H5
833
+ // uni.getFileInfo 在 app 和 h5 中可用
834
+ const [, fileInfo] = await uni.getFileInfo({
835
+ filePath: filePath
836
+ })
837
+
838
+ if (fileInfo && fileInfo.size !== undefined) {
839
+ fileInfos.push({
840
+ path: filePath,
841
+ size: fileInfo.size
842
+ })
843
+ } else {
844
+ // 如果无法获取文件信息,保持原路径(跳过大小检查)
845
+ fileInfos.push(filePath)
846
+ }
847
+ // #endif
848
+
849
+ // #ifndef APP-PLUS || H5
850
+ // 在小程序环境中,由于安全限制,可能无法获取文件大小
851
+ // 这种情况下跳过文件大小检查
852
+ fileInfos.push(filePath)
853
+ // #endif
854
+ } catch (error) {
855
+ console.log(TAG, '获取文件信息失败', error)
856
+ // 如果获取文件信息失败,保持原路径(跳过大小检查)
857
+ fileInfos.push(filePath)
858
+ }
859
+ }
860
+
861
+ return fileInfos
862
+ },
376
863
  async handleUpload(paths) {
377
864
  const beforeUpload = this.beforeUpload[PI_DEFAULT_FN_FLAG]
378
865
  ? this.beforeUpload.fn
379
866
  : this.beforeUpload
380
- const onProgress = this.onProgress[PI_DEFAULT_FN_FLAG] ? this.onProgress.fn : this.onProgress
867
+ const onProgress = this.onProgress[PI_DEFAULT_FN_FLAG]
868
+ ? this.onProgress.fn
869
+ : this.onProgress
381
870
  const parseResultFn = this.parseResultFn[PI_DEFAULT_FN_FLAG]
382
871
  ? this.parseResultFn.fn
383
872
  : this.parseResultFn
384
873
  try {
385
874
  for await (const filePath of paths) {
386
875
  // ---------- 上传之前的钩子 ----------
876
+ const file = filePath
387
877
 
388
878
  let beforeUploadResult = true
389
879
  if (this.$pi.lang.isFunction(beforeUpload)) {
390
880
  console.log(TAG, '调用文件上传前钩子')
391
- beforeUploadResult = await beforeUpload(filePath)
881
+ beforeUploadResult = await beforeUpload(
882
+ file,
883
+ this.customUploadParams
884
+ )
392
885
  }
393
886
  if (!beforeUploadResult) {
394
887
  console.log(TAG, '文件上传前钩子返回false,跳过上传')
@@ -400,7 +893,7 @@ export default {
400
893
  let uploadResult = null
401
894
  const params = {
402
895
  url: this.action,
403
- filePath: filePath,
896
+ filePath: file,
404
897
  name: this.name,
405
898
  formData: this.formData,
406
899
  header: this.headers
@@ -408,15 +901,19 @@ export default {
408
901
  if (this.$pi.lang.isFunction(onProgress)) {
409
902
  console.log(TAG, '使用自定义上传函数')
410
903
  // 上传之前的钩子, 如果定义了则使用钩子上传文件
411
- uploadResult = await onProgress(params)
904
+ uploadResult = await onProgress(params, this.customUploadParams)
412
905
  } else {
413
906
  const [, uploadFileResult] = await uni.uploadFile(params)
414
907
  uploadResult = uploadFileResult
415
908
  }
909
+ console.log(TAG, '上传文件结果', uploadResult)
416
910
 
417
911
  // ---------- 解析上传结果 ----------
418
912
  this.$emit('uploaded', uploadResult)
419
- const item = await parseResultFn(uploadResult)
913
+ const item = await parseResultFn(
914
+ uploadResult,
915
+ this.customUploadParams
916
+ )
420
917
  if (item) {
421
918
  this.isValString ? (this.val = item) : this.val.push(item)
422
919
  this.handleEmitChange()
@@ -438,16 +935,50 @@ export default {
438
935
  this.showCrop = false
439
936
  this.cropPic = ''
440
937
  },
441
- handleCompelteCrop() {
938
+ async handleCompelteCrop() {
442
939
  console.log(TAG, '完成剪裁')
443
940
  this.$emit('croped', [this.cropedPic])
444
941
  this.showCrop = false
445
- this.handleUpload([this.cropedPic])
942
+
943
+ // 剪裁完成后也要检查文件大小
944
+ const tempFilesWithSize = await this.getFileInfoForPaths([this.cropedPic])
945
+ const sizeCheckResult = this.checkFileSize(tempFilesWithSize)
946
+
947
+ if (sizeCheckResult.valid && sizeCheckResult.files.length > 0) {
948
+ const validPaths = sizeCheckResult.files.map(file => file.path || file)
949
+ this.handleUpload(validPaths)
950
+ }
446
951
  },
447
- async handleChooseImage() {
952
+ async handleCompressImgs(tempFilePaths) {
953
+ const compressUrls = []
954
+
955
+ for (let index = 0; index < tempFilePaths.length; index++) {
956
+ const url = tempFilePaths[index]
957
+ const [, result] = await uni.compressImage({
958
+ src: url,
959
+ ...this.compressOption
960
+ })
961
+ const { errMsg, tempFilePath } = result
962
+ if (
963
+ errMsg == 'compressImage:ok' &&
964
+ tempFilePath &&
965
+ typeof tempFilePath == 'string'
966
+ ) {
967
+ compressUrls.push(tempFilePath)
968
+ console.log(TAG, '压缩图片成功', tempFilePath, 'src=' + url)
969
+ } else {
970
+ compressUrls.push(url)
971
+ console.log(TAG, '压缩图片成功', tempFilePath, 'src=' + url)
972
+ }
973
+ }
974
+ return compressUrls
975
+ },
976
+ handleChoose() {
448
977
  if (this.disabled || !this.getUploadMaxCount) return
449
978
  // 检查上传地址
450
- const onProgress = this.onProgress[PI_DEFAULT_FN_FLAG] ? this.onProgress.fn : this.onProgress
979
+ const onProgress = this.onProgress[PI_DEFAULT_FN_FLAG]
980
+ ? this.onProgress.fn
981
+ : this.onProgress
451
982
  if (!onProgress && !this.action) {
452
983
  this.$toast('请配置上传地址')
453
984
  return
@@ -455,30 +986,335 @@ export default {
455
986
  if (this.$pi.lang.isEmpty(this.headers)) {
456
987
  console.log(TAG, '当前图片上传headers为空,请检查是否需要配置授权信息')
457
988
  }
458
- const { sizeType, extension, sourceType, crop } = this.getChooseImageOpts
989
+ console.log('当前上传文件类型:', this.type)
990
+ if (this.type === 'all') {
991
+ // #ifndef MP-WEIXIN
992
+ this.handleChooseFile()
993
+ // #endif
994
+
995
+ // #ifdef MP-WEIXIN
996
+ const { fromWxMessage } = this.getChooseFileOpts
997
+ if (fromWxMessage) {
998
+ if (this.selectOnlyFile) {
999
+ this.handleSelectMessageFile()
1000
+ return
1001
+ }
1002
+ this.$emit('show-actions')
1003
+ this.showActionSheet = true
1004
+ } else {
1005
+ this.handleChooseMedia()
1006
+ }
1007
+ // #endif
1008
+
1009
+ return
1010
+ }
1011
+ if (this.type === 'image') {
1012
+ this.handleChooseImage()
1013
+ return
1014
+ }
1015
+ if (this.type === 'video') {
1016
+ // #ifndef MP-WEIXIN
1017
+ this.handleChooseVideo()
1018
+ // #endif
1019
+
1020
+ // #ifdef MP-WEIXIN
1021
+ this.handleChooseMedia()
1022
+ // #endif
1023
+
1024
+ return
1025
+ }
1026
+ },
1027
+ async handleChooseFile() {
1028
+ const { sizeType, sourceType, crop } = this.getChooseFileOpts
1029
+ try {
1030
+ const [cancel, result] = await uni.chooseFile({
1031
+ count: this.getUploadMaxCount,
1032
+ sizeType,
1033
+ sourceType,
1034
+ crop
1035
+ })
1036
+
1037
+ if (cancel && cancel?.errMsg === 'chooseFile:fail cancel') {
1038
+ console.log(TAG, '用户取消选择文件')
1039
+ return
1040
+ }
1041
+
1042
+ let { errMsg, tempFiles } = result
1043
+ console.log(TAG, '上传文件结果', result)
1044
+ if (errMsg !== 'chooseFile:ok') {
1045
+ throw new Error(errMsg)
1046
+ }
1047
+
1048
+ // 检查文件大小限制
1049
+ const sizeCheckResult = this.checkFileSize(tempFiles)
1050
+ if (sizeCheckResult.valid && sizeCheckResult.files.length > 0) {
1051
+ this.handleUpload(sizeCheckResult.files)
1052
+ }
1053
+ } catch (error) {
1054
+ console.log(TAG, '上传文件失败', error)
1055
+ this.$emit('fail', error)
1056
+ }
1057
+ },
1058
+ // 从微信聊天会话中选择文件
1059
+ async handleSelectMessageFile() {
1060
+ // #ifndef MP-WEIXIN
1061
+ this.$toast('请在微信小程序中使用')
1062
+ // #endif
1063
+
1064
+ console.log('从微信聊天会话中选择文件')
1065
+
1066
+ // #ifdef MP-WEIXIN
1067
+ this.showSheet = false
459
1068
  try {
460
- const [, result] = await uni.chooseImage({
1069
+ const [cancel, result] = await uni.chooseMessageFile({
1070
+ count: this.getUploadMaxCount,
1071
+ type:
1072
+ this.fileTypes.includes('image') || this.fileTypes.includes('video')
1073
+ ? 'all'
1074
+ : 'file'
1075
+ })
1076
+ if (cancel && cancel?.errMsg === 'chooseMessageFile:fail cancel') {
1077
+ console.log(TAG, '用户取消选择聊天文件')
1078
+ return
1079
+ }
1080
+
1081
+ let { errMsg, tempFiles } = result
1082
+ console.log(TAG, '选择微信聊天记录文件', result)
1083
+ if (errMsg !== 'chooseMessageFile:ok') {
1084
+ throw new Error(errMsg)
1085
+ }
1086
+ // chooseMessageFile 没有扩展名限制,这里自己做过滤
1087
+ tempFiles = tempFiles.filter(file => {
1088
+ return this.isRightType(file)
1089
+ })
1090
+ console.log(TAG, '过滤后的文件列表:', tempFiles)
1091
+
1092
+ // 检查文件大小限制
1093
+ const sizeCheckResult = this.checkFileSize(tempFiles)
1094
+ if (sizeCheckResult.valid && sizeCheckResult.files.length > 0) {
1095
+ this.handleUpload(sizeCheckResult.files)
1096
+ }
1097
+ } catch (error) {
1098
+ console.log(error)
1099
+ }
1100
+ // #endif
1101
+ },
1102
+ async handleChooseImage() {
1103
+ const { sizeType, sourceType, crop } = this.getChooseImageOpts
1104
+
1105
+ this.currentSourceType = sourceType
1106
+
1107
+ if (this.customTakePhoto) {
1108
+ this.showCustomTakePhoto = true
1109
+ return
1110
+ }
1111
+
1112
+ this.handleUniChooseImage(sizeType, sourceType, crop)
1113
+ },
1114
+ async handleUniChooseImage(sizeType, sourceType, crop) {
1115
+ try {
1116
+ const [cancel, result] = await uni.chooseImage({
461
1117
  count: this.getUploadMaxCount,
462
1118
  sizeType,
463
- extension,
464
1119
  sourceType,
465
1120
  crop
466
1121
  })
467
- const { errMsg, tempFilePaths } = result
1122
+
1123
+ if (cancel && cancel?.errMsg === 'chooseImage:fail cancel') {
1124
+ console.log(TAG, '用户取消选择图片')
1125
+ return
1126
+ }
1127
+
1128
+ let { errMsg, tempFilePaths } = result
468
1129
  if (errMsg !== 'chooseImage:ok') {
469
1130
  throw new Error(errMsg)
470
1131
  }
471
- if (this.getUploadMaxCount === 1 && this.crop && tempFilePaths.length === 1) {
472
- // 单张图片设置了剪裁
1132
+ // #ifndef H5
1133
+ // 压缩图片
1134
+ if (
1135
+ this.compressOption &&
1136
+ this.$pi.system.systemInfo.platform !== 'devtools'
1137
+ ) {
1138
+ tempFilePaths = await this.handleCompressImgs(tempFilePaths)
1139
+ }
1140
+ // #endif
1141
+ if (
1142
+ this.getUploadMaxCount === 1 &&
1143
+ this.crop &&
1144
+ tempFilePaths.length === 1
1145
+ ) {
1146
+ // 单张图片设置了剪裁,暂时不进行文件大小检查,在剪裁完成后再检查
473
1147
  this.showCrop = true
474
1148
  this.cropPic = tempFilePaths[0]
475
1149
  return
476
1150
  }
477
- this.handleUpload(tempFilePaths)
1151
+
1152
+ // 对于选择的图片路径,我们需要构造合适的文件对象进行大小检查
1153
+ // uni-app 的 chooseImage 返回的 tempFilePaths 不包含文件大小信息
1154
+ // 所以我们需要获取文件信息
1155
+ const tempFilesWithSize = await this.getFileInfoForPaths(tempFilePaths)
1156
+ const sizeCheckResult = this.checkFileSize(tempFilesWithSize)
1157
+
1158
+ if (sizeCheckResult.valid && sizeCheckResult.files.length > 0) {
1159
+ // 恢复为路径数组格式传递给 handleUpload
1160
+ const validPaths = sizeCheckResult.files.map(
1161
+ file => file.path || file
1162
+ )
1163
+ this.handleUpload(validPaths)
1164
+ }
478
1165
  } catch (error) {
479
- console.log(TAG, '上传文件失败', e)
1166
+ console.log(TAG, '上传文件失败', error)
480
1167
  this.$emit('fail', error)
481
1168
  }
1169
+ },
1170
+ async handleChooseVideo() {
1171
+ const { sourceType, maxDuration, camera } = this.getChooseVideoOpts
1172
+
1173
+ this.currentSourceType = sourceType
1174
+
1175
+ if (this.customTakePhoto) {
1176
+ this.showCustomTakePhoto = true
1177
+ return
1178
+ }
1179
+
1180
+ try {
1181
+ const [cancel, result] = await uni.chooseVideo({
1182
+ sourceType,
1183
+ maxDuration,
1184
+ camera
1185
+ })
1186
+
1187
+ if (cancel && cancel?.errMsg === 'chooseVideo:fail cancel') {
1188
+ console.log(TAG, '用户取消选择视频')
1189
+ return
1190
+ }
1191
+
1192
+ let { errMsg, tempFilePath, tempFile } = result
1193
+ if (errMsg !== 'chooseVideo:ok') {
1194
+ throw new Error(errMsg)
1195
+ }
1196
+ tempFile.path = tempFilePath
1197
+ console.log(TAG, '上传视频结果', result)
1198
+
1199
+ // 检查文件大小限制
1200
+ const sizeCheckResult = this.checkFileSize([tempFile])
1201
+ if (sizeCheckResult.valid && sizeCheckResult.files.length > 0) {
1202
+ this.handleUpload(sizeCheckResult.files)
1203
+ }
1204
+ } catch (error) {
1205
+ console.log(TAG, '上传视频失败', error)
1206
+ this.$emit('fail', error)
1207
+ }
1208
+ },
1209
+ async handleChooseMedia() {
1210
+ const { sourceType, maxDuration, camera } =
1211
+ this.type === 'video' ? this.getChooseVideoOpts : this.getChooseFileOpts
1212
+
1213
+ this.currentSourceType = sourceType
1214
+
1215
+ if (this.customTakePhoto) {
1216
+ this.showCustomTakePhoto = true
1217
+ return
1218
+ }
1219
+
1220
+ try {
1221
+ const [cancel, result] = await uni.chooseMedia({
1222
+ count: this.getUploadMaxCount,
1223
+ mediaType: this.type === 'video' ? ['video'] : ['mix'],
1224
+ extension: this.getExtension,
1225
+ sourceType,
1226
+ maxDuration,
1227
+ camera
1228
+ })
1229
+
1230
+ if (cancel && cancel?.errMsg === 'chooseMedia:fail cancel') {
1231
+ console.log(TAG, '用户取消选择媒体')
1232
+ return
1233
+ }
1234
+
1235
+ let { errMsg, tempFiles } = result
1236
+ if (errMsg !== 'chooseMedia:ok') {
1237
+ throw new Error(errMsg)
1238
+ }
1239
+ console.log(TAG, '上传媒体结果', result)
1240
+
1241
+ // #ifndef H5
1242
+ // 非H5端/开发者工具,上传视频,执行压缩视频操作
1243
+ if (this.$pi.system.systemInfo.platform !== 'devtools') {
1244
+ const compressTempFiles = []
1245
+ for await (const tempFile of tempFiles) {
1246
+ const tempFilePath = tempFile.tempFilePath
1247
+ let filePath = ''
1248
+ if (isImageFilename(tempFilePath)) {
1249
+ const filePaths = await this.handleCompressImgs([
1250
+ tempFile.tempFilePath
1251
+ ])
1252
+ filePath = filePaths[0]
1253
+ } else {
1254
+ filePath = await this.handleCompressVideo(tempFile.tempFilePath)
1255
+ }
1256
+
1257
+ compressTempFiles.push(filePath)
1258
+ }
1259
+ this.handleUpload(compressTempFiles)
1260
+ return
1261
+ }
1262
+ // #endif
1263
+
1264
+ // 检查文件大小限制
1265
+ const sizeCheckResult = this.checkFileSize(tempFiles)
1266
+ if (sizeCheckResult.valid && sizeCheckResult.files.length > 0) {
1267
+ this.handleUpload(
1268
+ sizeCheckResult.files.map(file => file.tempFilePath || file)
1269
+ )
1270
+ }
1271
+ } catch (error) {
1272
+ console.log(TAG, '上传视频失败', error)
1273
+ this.$emit('fail', error)
1274
+ }
1275
+ },
1276
+ // 压缩视频接口
1277
+ async handleCompressVideo(tempUrl) {
1278
+ console.log('视频压缩中')
1279
+ uni.showLoading({
1280
+ title: '视频压缩中...'
1281
+ })
1282
+ const [, result] = await uni.compressVideo({
1283
+ src: tempUrl,
1284
+ quality: 'high' // 压缩质量 支持low, medium, high
1285
+ })
1286
+ uni.hideLoading()
1287
+ const { errMsg, tempFilePath } = result
1288
+ if (errMsg == 'compressVideo:ok') {
1289
+ return tempFilePath
1290
+ }
1291
+ return tempUrl
1292
+ },
1293
+ handleActionSheetSelect(type) {
1294
+ if (type.id === 1) {
1295
+ this.handleChooseMedia()
1296
+ } else {
1297
+ this.handleSelectMessageFile()
1298
+ }
1299
+ },
1300
+ handleEmitTakePhoto(takeType) {
1301
+ this.$emit('customTakePhoto', {
1302
+ takeType,
1303
+ uploadType: this.type,
1304
+ compressOption: this.compressOption,
1305
+ chooseImageOpts: this.getChooseImageOpts,
1306
+ chooseVideoOpts: this.getChooseVideoOpts,
1307
+ chooseFileOpts: this.getChooseFileOpts
1308
+ })
1309
+ },
1310
+ handleCustomTakePhotoSelect(type) {
1311
+ if (type.id === 'chooseFromAlbum') {
1312
+ // 从手机相册选择
1313
+ const { sizeType, crop } = this.getChooseImageOpts
1314
+ this.handleUniChooseImage(sizeType, ['album'], crop)
1315
+ } else {
1316
+ this.handleEmitTakePhoto(type.id)
1317
+ }
482
1318
  }
483
1319
  }
484
1320
  }
@@ -508,5 +1344,20 @@ export default {
508
1344
  margin-right: 24rpx;
509
1345
  margin-bottom: 24rpx;
510
1346
  }
1347
+ .file-mask {
1348
+ position: absolute;
1349
+ top: 0;
1350
+ left: 0;
1351
+ width: 100%;
1352
+ height: 100%;
1353
+ display: flex;
1354
+ flex-direction: column;
1355
+ align-items: center;
1356
+ justify-content: center;
1357
+ background: rgba(0, 0, 0, 0.3);
1358
+ &.no-bg {
1359
+ background: transparent;
1360
+ }
1361
+ }
511
1362
  }
512
1363
  </style>