sadais-piui 1.2.7-beta113 → 1.2.7-beta115

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 (160) hide show
  1. package/.prettierrc +7 -7
  2. package/CHANGELOG.md +545 -545
  3. package/LICENSE +20 -20
  4. package/README.md +166 -166
  5. package/components/pi-action-sheet/index.vue +247 -247
  6. package/components/pi-badge/index.vue +146 -146
  7. package/components/pi-bottom-bar/index.vue +139 -139
  8. package/components/pi-bubble/index.vue +174 -174
  9. package/components/pi-button/index.vue +492 -492
  10. package/components/pi-calendar-input/index.vue +230 -230
  11. package/components/pi-calendar-panel/components/calendar-days/index.vue +410 -410
  12. package/components/pi-calendar-panel/index.vue +473 -473
  13. package/components/pi-canvas/index.vue +407 -407
  14. package/components/pi-card/index.vue +127 -127
  15. package/components/pi-cascader/index.vue +601 -601
  16. package/components/pi-checkbox/index.vue +363 -363
  17. package/components/pi-checkbox-group/index.vue +222 -222
  18. package/components/pi-circle-progress/index.vue +311 -311
  19. package/components/pi-code-input/index.vue +270 -270
  20. package/components/pi-collapse/index.vue +124 -124
  21. package/components/pi-collapse-item/index.vue +352 -352
  22. package/components/pi-count-down/index.vue +245 -245
  23. package/components/pi-count-up/index.vue +209 -209
  24. package/components/pi-date-picker-input/index.vue +219 -219
  25. package/components/pi-divider/index.vue +112 -112
  26. package/components/pi-dropdown/components/dropdown-tab.vue +71 -71
  27. package/components/pi-dropdown/index.vue +356 -356
  28. package/components/pi-dropdown-item/index.vue +252 -252
  29. package/components/pi-form/index.vue +273 -273
  30. package/components/pi-form-item/index.vue +603 -590
  31. package/components/pi-gap/index.vue +72 -72
  32. package/components/pi-grid/index.vue +92 -92
  33. package/components/pi-grid-item/index.vue +220 -220
  34. package/components/pi-icon/index.vue +147 -147
  35. package/components/pi-img/index.vue +266 -266
  36. package/components/pi-img-cropper/canvas.js +106 -106
  37. package/components/pi-img-cropper/index.vue +357 -357
  38. package/components/pi-img-cropper/touch.js +163 -163
  39. package/components/pi-img-cropper/vector.js +34 -34
  40. package/components/pi-input/index.vue +409 -401
  41. package/components/pi-line/index.vue +78 -78
  42. package/components/pi-line-progress/index.vue +198 -198
  43. package/components/pi-list/index.vue +115 -115
  44. package/components/pi-list-item/index.vue +335 -335
  45. package/components/pi-loading/index.vue +188 -188
  46. package/components/pi-marquee/index.vue +310 -310
  47. package/components/pi-marquee-item/index.vue +47 -47
  48. package/components/pi-mask/index.vue +198 -198
  49. package/components/pi-modal/index.vue +303 -303
  50. package/components/pi-navbar/index.vue +421 -421
  51. package/components/pi-notify/index.vue +239 -239
  52. package/components/pi-number-keyboard/index.vue +189 -189
  53. package/components/pi-opentype-button/index.vue +501 -501
  54. package/components/pi-pagination/index.vue +290 -290
  55. package/components/pi-picker/index.vue +317 -317
  56. package/components/pi-popup/index.vue +356 -356
  57. package/components/pi-popup-select/index.vue +300 -300
  58. package/components/pi-radio/index.vue +403 -403
  59. package/components/pi-radio-group/index.vue +300 -300
  60. package/components/pi-rate/index.vue +212 -212
  61. package/components/pi-regions-select/index.vue +349 -349
  62. package/components/pi-regions-select-input/index.vue +230 -230
  63. package/components/pi-search/index.vue +386 -386
  64. package/components/pi-section/index.vue +218 -218
  65. package/components/pi-select/index.vue +678 -678
  66. package/components/pi-select-input/index.vue +273 -273
  67. package/components/pi-skeleton/index.vue +280 -280
  68. package/components/pi-status-bar/index.vue +56 -56
  69. package/components/pi-stepper/index.vue +408 -408
  70. package/components/pi-steps/index.vue +378 -378
  71. package/components/pi-subsection/index.vue +403 -403
  72. package/components/pi-swiper/index.vue +344 -344
  73. package/components/pi-switch/index.vue +231 -231
  74. package/components/pi-table/index.vue +351 -351
  75. package/components/pi-tabs/index.vue +435 -435
  76. package/components/pi-tag/index.vue +488 -488
  77. package/components/pi-upload-img/index.vue +980 -980
  78. package/components/pi-waterfall/index.vue +130 -130
  79. package/config/actionSheet.js +24 -24
  80. package/config/badge.js +9 -9
  81. package/config/bottomBar.js +11 -11
  82. package/config/bubble.js +6 -6
  83. package/config/button.js +29 -29
  84. package/config/calendar.js +19 -19
  85. package/config/calendarInput.js +19 -19
  86. package/config/calendarPanel.js +27 -27
  87. package/config/card.js +8 -8
  88. package/config/cascader.js +22 -22
  89. package/config/checkbox.js +15 -15
  90. package/config/checkboxGroup.js +15 -15
  91. package/config/circleProgress.js +20 -20
  92. package/config/codeInput.js +13 -13
  93. package/config/collapse.js +7 -7
  94. package/config/collapseItem.js +11 -11
  95. package/config/countDown.js +12 -12
  96. package/config/countUp.js +13 -13
  97. package/config/datePickerInput.js +18 -18
  98. package/config/divider.js +10 -10
  99. package/config/dropdown.js +25 -25
  100. package/config/dropdownItem.js +26 -26
  101. package/config/form.js +29 -29
  102. package/config/formItem.js +27 -27
  103. package/config/gap.js +8 -8
  104. package/config/grid.js +9 -9
  105. package/config/gridItem.js +12 -12
  106. package/config/icon.js +11 -11
  107. package/config/img.js +21 -21
  108. package/config/imgCropper.js +26 -26
  109. package/config/index.js +28 -28
  110. package/config/input.js +37 -36
  111. package/config/line.js +8 -8
  112. package/config/lineProgress.js +14 -14
  113. package/config/list.js +12 -12
  114. package/config/listItem.js +25 -25
  115. package/config/loading.js +10 -10
  116. package/config/marquee.js +10 -10
  117. package/config/mask.js +12 -12
  118. package/config/modal.js +36 -36
  119. package/config/navbar.js +32 -32
  120. package/config/notify.js +13 -13
  121. package/config/numberKeyboard.js +21 -21
  122. package/config/pagination.js +10 -10
  123. package/config/picker.js +19 -19
  124. package/config/popup.js +23 -23
  125. package/config/popupSelect.js +35 -35
  126. package/config/radio.js +16 -16
  127. package/config/radioGroup.js +17 -17
  128. package/config/rate.js +15 -15
  129. package/config/regionsData.js +58 -58
  130. package/config/regionsSelect.js +19 -19
  131. package/config/regionsSelectInput.js +29 -29
  132. package/config/search.js +27 -27
  133. package/config/section.js +23 -23
  134. package/config/select.js +41 -41
  135. package/config/selectInput.js +29 -29
  136. package/config/skeleton.js +13 -13
  137. package/config/statusBar.js +5 -5
  138. package/config/stepper.js +19 -19
  139. package/config/steps.js +19 -19
  140. package/config/subsection.js +14 -14
  141. package/config/swiper.js +22 -22
  142. package/config/switch.js +13 -13
  143. package/config/table.js +8 -8
  144. package/config/tabs.js +23 -23
  145. package/config/tag.js +21 -21
  146. package/config/uploadImg.js +81 -81
  147. package/config/waterfall.js +6 -6
  148. package/index.js +41 -41
  149. package/mixin/component-custom.js +24 -24
  150. package/mixin/emitter.js +45 -45
  151. package/mixin/props-sync.js +65 -65
  152. package/mixin/value-sync.js +32 -32
  153. package/mixin/wx-code.js +30 -30
  154. package/package.json +28 -28
  155. package/plugins/async-validator.js +1511 -1511
  156. package/scss/animation.scss +260 -260
  157. package/scss/icon/icon.scss +595 -595
  158. package/scss/index.scss +5 -5
  159. package/scss/mixin.scss +47 -47
  160. package/tools/index.js +19 -19
@@ -1,980 +1,980 @@
1
- <!--
2
- * @Author: zhangzhenfei
3
- * @Date: 2021-08-13 11:31:57
4
- * @LastEditTime: 2024-06-11 11:39:08
5
- * @LastEditors: zhangzhenfei
6
- * @Description: 图片上传组件
7
- * @FilePath: /piui-awesome/src/piui/components/pi-upload-img/index.vue
8
- -->
9
-
10
- <template>
11
- <view
12
- class="pi-upload-img"
13
- :style="[customStyle]"
14
- :class="[customClass, { 'pi-pd-top-12': !getDisabled }]"
15
- >
16
- <!-- 已上传图片展示 -->
17
- <view
18
- v-for="(img, index) in getImgs"
19
- :key="index"
20
- class="pi-rela pi-flex-column-center"
21
- @tap="handlePreview(img)"
22
- >
23
- <view v-if="!getDisabled" class="close" @tap.stop="handleDelete(index)">
24
- <pi-icon name="roundclosefill" color="#8e8e8e" size="36" />
25
- </view>
26
- <image
27
- v-if="isImageFilename(imgField ? img[imgField] : img)"
28
- :style="[getItemStyle]"
29
- class="pi-of-hidden"
30
- :mode="imageMode"
31
- :src="imgField ? img[imgField] : img"
32
- />
33
- <view
34
- v-else
35
- class="pi-rela pi-of-hidden pi-radius-8"
36
- :style="[getItemStyle]"
37
- >
38
- <view class="file-mask">
39
- <pi-icon
40
- :name="
41
- isVideoFilename(imgField ? img[imgField] : img)
42
- ? 'videofill'
43
- : 'activity-fill'
44
- "
45
- size="48"
46
- color="#0C6DF4"
47
- />
48
- <view class="pi-mg-top-12 pi-fz-22">
49
- {{ getFileType(imgField ? img[imgField] : img) }}
50
- </view>
51
- </view>
52
- </view>
53
- </view>
54
- <!-- 上传框 -->
55
- <view v-if="getUploadMaxCount && !getDisabled">
56
- <view
57
- :style="[getUploadBtnStyle]"
58
- class="pi-flex-column-center"
59
- @tap="handleChoose"
60
- >
61
- <slot name="uploadBtn">
62
- <!-- 添加按钮 -->
63
- <pi-icon
64
- :custom-style="getUploadIcon.customStyle"
65
- :custom-class="getUploadIcon.customClass"
66
- :name="getUploadIcon.name"
67
- :dot="getUploadIcon.dot"
68
- :dot-radius="getUploadIcon.dotRadius"
69
- :badge="getUploadIcon.badge"
70
- :color="getUploadIcon.color"
71
- :size="getUploadIcon.size"
72
- :class-prefix="getUploadIcon.classPrefix"
73
- />
74
- </slot>
75
- <view v-if="uploadText" class="pi-mg-top-6 pi-fz-24 pi-light-gray">{{
76
- uploadText
77
- }}</view>
78
- </view>
79
- </view>
80
- <!-- 剪裁弹窗 -->
81
- <pi-mask
82
- v-model="showCrop"
83
- :mask-closeable="false"
84
- background="rgba(0, 0, 0, .9)"
85
- >
86
- <view class="pi-abso-full pi-flex-column">
87
- <view class="pi-flex-sub">
88
- <pi-img-cropper
89
- :custom-style="getCropOption.customStyle"
90
- :custom-class="getCropOption.customClass"
91
- :src="cropPic"
92
- :file-type="getCropOption.fileType"
93
- :quality="getCropOption.quality"
94
- :crop-size="getCropOption.cropSize"
95
- :min-crop-size="getCropOption.minCropSize"
96
- :boundary-detect="getCropOption.boundaryDetect"
97
- :keep-crop-ratio="getCropOption.keepCropRatio"
98
- :disable-rotate="getCropOption.disableRotate"
99
- :canvas-zoom="getCropOption.canvasZoom"
100
- :mask-background="getCropMaskBackground"
101
- @cropped="handleCrop"
102
- />
103
- </view>
104
- <pi-bottom-bar
105
- border-top="none"
106
- :background="getCropMaskBackground"
107
- :safe-area-bg-color="getCropMaskBackground"
108
- >
109
- <view
110
- class="pi-justify-between pi-align-center pi-pd-tb-32 pi-pd-lr-24 pi-fz-32"
111
- >
112
- <view class="pi-white" @tap="handleCancelCrop">取消</view>
113
- <view class="pi-primary" @tap="handleCompelteCrop">完成</view>
114
- </view>
115
- </pi-bottom-bar>
116
- </view>
117
- </pi-mask>
118
- <!-- 上传视频操作面板(小程序专用) -->
119
- <pi-action-sheet
120
- v-model="showActionSheet"
121
- :items="actionSheetItems"
122
- :popup="{
123
- borderRadius: 0
124
- }"
125
- @select="handleActionSheetSelect"
126
- />
127
- </view>
128
- </template>
129
-
130
- <script>
131
- /**
132
- * 通过v-model控制蒙层是否显示
133
- * input 蒙层显示或者关闭的时候触发事件 value: boolean (蒙层是否显示)
134
- */
135
- import ValueSync from '../../mixin/value-sync'
136
- import { getConfig } from '../../config'
137
-
138
- const TAG = 'PiUploadImg'
139
- const { uploadImg } = getConfig()
140
-
141
- const PI_DEFAULT_FN_FLAG = 'PI_DEFAULT_FN_FLAG'
142
-
143
- function isImageFilename(filename) {
144
- const imageExtensions = /\.(jpg|jpeg|png|gif|bmp|tiff|webp)$/i
145
- return imageExtensions.test(filename)
146
- }
147
-
148
- function isVideoFilename(filename) {
149
- const videoExtensions = /\.(mp4|avi|mov|wmv|mpg|flv|mkv)$/i
150
- return videoExtensions.test(filename)
151
- }
152
-
153
- export default {
154
- name: 'PiUploadImg',
155
- // 混入v-model
156
- mixins: [ValueSync],
157
- props: {
158
- // 初始值
159
- value: {
160
- required: false,
161
- type: [Array, String],
162
- default() {
163
- return []
164
- }
165
- },
166
- // 自定义样式
167
- customStyle: {
168
- type: Object,
169
- default() {
170
- // {}
171
- return uploadImg.customStyle
172
- }
173
- },
174
- // 自定义样式类
175
- customClass: {
176
- type: String,
177
- default() {
178
- // ''
179
- return uploadImg.customClass
180
- }
181
- },
182
- // 上传按钮样式
183
- itemStyle: {
184
- type: Object,
185
- default() {
186
- // {}
187
- return uploadImg.itemStyle
188
- }
189
- },
190
- // 上传按钮样式
191
- uploadBtnStyle: {
192
- type: Object,
193
- default() {
194
- // {}
195
- return uploadImg.uploadBtnStyle
196
- }
197
- },
198
- // 上传图片的字段名称,字符串形式(默认值:'')
199
- imgField: {
200
- type: String,
201
- default() {
202
- return uploadImg.imgField
203
- }
204
- },
205
- // 显示的图片模式
206
- imageMode: {
207
- type: String,
208
- default() {
209
- // 'aspectFill'
210
- return uploadImg.imageMode
211
- }
212
- },
213
- // 上传接口地址,字符串形式(默认值:'')
214
- action: {
215
- type: String,
216
- default() {
217
- return uploadImg.action
218
- }
219
- },
220
- // 请求头,对象形式(默认值:{})
221
- headers: {
222
- type: Object,
223
- default() {
224
- return uploadImg.headers
225
- }
226
- },
227
- // 上传表单额外数据,对象形式(默认值:{})
228
- formData: {
229
- type: Object,
230
- default() {
231
- return uploadImg.formData
232
- }
233
- },
234
- // 上传的文件字段名
235
- name: {
236
- type: String,
237
- default() {
238
- return uploadImg.name
239
- }
240
- },
241
- // 上传区域尺寸(半径)
242
- size: {
243
- type: [String, Number],
244
- default() {
245
- // ''
246
- return uploadImg.size
247
- }
248
- },
249
- // 是否在点击预览图后展示全屏图片预览
250
- previewFullImage: {
251
- type: Boolean,
252
- default() {
253
- return uploadImg.previewFullImage
254
- }
255
- },
256
- // 是否可以删除上传的文件
257
- deletable: {
258
- type: Boolean,
259
- default() {
260
- return uploadImg.deletable
261
- }
262
- },
263
- // 是否禁用上传
264
- disabled: {
265
- type: Boolean,
266
- default() {
267
- return uploadImg.disabled
268
- }
269
- },
270
- // 上传文件的最大数量
271
- maxCount: {
272
- type: [String, Number],
273
- default() {
274
- return uploadImg.maxCount
275
- }
276
- },
277
- // 上传区域文字提示
278
- uploadText: {
279
- type: String,
280
- default() {
281
- return uploadImg.uploadText
282
- }
283
- },
284
- // 上传区域图标
285
- uploadIcon: {
286
- type: Object,
287
- default() {
288
- return uploadImg.uploadIcon
289
- }
290
- },
291
- // 当maxCount设置为1的时候,且type为‘image’,可开启裁剪
292
- crop: {
293
- type: Boolean,
294
- // `false`
295
- default: uploadImg.crop
296
- },
297
- // 裁剪参数
298
- cropOption: {
299
- type: Object,
300
- default() {
301
- return uploadImg.cropOption
302
- }
303
- },
304
- // 上传成功解析对象方法
305
- parseResultFn: {
306
- type: [Object, Function],
307
- default() {
308
- return {
309
- [PI_DEFAULT_FN_FLAG]: true,
310
- fn: uploadImg.parseResultFn
311
- }
312
- }
313
- },
314
- // 上传之前的钩子
315
- beforeUpload: {
316
- type: [Object, Function],
317
- default() {
318
- return {
319
- [PI_DEFAULT_FN_FLAG]: true,
320
- fn: uploadImg.beforeUpload
321
- }
322
- }
323
- },
324
- // 文件上传时的钩子
325
- onProgress: {
326
- type: [Object, Function],
327
- default() {
328
- return {
329
- [PI_DEFAULT_FN_FLAG]: true,
330
- fn: uploadImg.onProgress
331
- }
332
- }
333
- },
334
- // 删除之前的钩子
335
- beforeRemove: {
336
- type: [Object, Function],
337
- default() {
338
- return {
339
- [PI_DEFAULT_FN_FLAG]: true,
340
- fn: uploadImg.beforeRemove
341
- }
342
- }
343
- },
344
- // 压缩参数
345
- compressOption: {
346
- type: Object,
347
- default() {
348
- return uploadImg.compressOption
349
- }
350
- },
351
- // 文件类型
352
- type: {
353
- type: String,
354
- default() {
355
- return uploadImg.type // 'all', 'image', 'video'
356
- }
357
- },
358
- // 当 type 为 all 时生效,允许上传的文件类型是否包含 video 和 image
359
- fileTypes: {
360
- type: Array,
361
- default() {
362
- return uploadImg.fileTypes
363
- }
364
- },
365
- // 当type为 "all"时生效,调用uni.chooseFile参数
366
- chooseFileOpts: {
367
- type: Object,
368
- default() {
369
- return uploadImg.chooseFileOpts
370
- }
371
- },
372
- // 当type为 "image"时生效,调用uni.chooseImage参数
373
- chooseImageOpts: {
374
- type: Object,
375
- default() {
376
- return uploadImg.chooseImageOpts
377
- }
378
- },
379
- // 当type为 "video"时生效,调用uniapp.chooseVideo参数
380
- chooseVideoOpts: {
381
- type: Object,
382
- default() {
383
- return uploadImg.chooseVideoOpts
384
- }
385
- }
386
- },
387
- data() {
388
- return {
389
- showCrop: false, // 是否显示裁剪工具
390
- cropPic: '', // 需要剪裁的图片
391
- cropedPic: '', // 剪裁后的图片
392
- showActionSheet: false // 是否显示上传视频操作面板
393
- }
394
- },
395
- computed: {
396
- getDisabled() {
397
- const parent = this.$pi.parent(this, 'PiFormItem')
398
- return this.disabled || (parent && parent.getDisabled)
399
- },
400
- actionSheetItems() {
401
- return [
402
- {
403
- id: 1,
404
- text: '选择媒体图片/视频'
405
- },
406
- {
407
- id: 2,
408
- text: '选择微信聊天文件'
409
- }
410
- ]
411
- },
412
- isValString() {
413
- return this.$pi.lang.isString(this.val)
414
- },
415
- getImgs() {
416
- if (this.val === null || this.val === undefined) {
417
- return []
418
- }
419
- return this.isValString
420
- ? this.val
421
- ? [this.val]
422
- : []
423
- : this.val.filter(img => img)
424
- },
425
- getItemStyle() {
426
- const style = {
427
- width: this.getSize,
428
- height: this.getSize
429
- }
430
- const uploadStyle = this.$pi.lang.mergeDeep(
431
- uploadImg.itemStyle,
432
- this.itemStyle
433
- )
434
- return this.$pi.lang.mergeDeep(style, uploadStyle)
435
- },
436
- getSize() {
437
- return this.$pi.common.addUnit(this.size)
438
- },
439
- getUploadBtnStyle() {
440
- const style = {
441
- width: this.getSize,
442
- height: this.getSize
443
- }
444
- const uploadBtnStyle = this.$pi.lang.mergeDeep(
445
- uploadImg.uploadBtnStyle,
446
- this.uploadBtnStyle
447
- )
448
- return this.$pi.lang.mergeDeep(style, uploadBtnStyle)
449
- },
450
- getUploadIcon() {
451
- return this.$pi.lang.mergeDeep(uploadImg.uploadIcon, this.uploadIcon)
452
- },
453
- getChooseImageOpts() {
454
- // 以覆盖的方式合并数组
455
- return this.$pi.lang.mergeDeep(
456
- uploadImg.chooseImageOpts,
457
- this.chooseImageOpts,
458
- {
459
- arrayMerge: (_target, source) => source
460
- }
461
- )
462
- },
463
- getChooseFileOpts() {
464
- return this.$pi.lang.mergeDeep(
465
- uploadImg.chooseFileOpts,
466
- this.chooseFileOpts,
467
- {
468
- arrayMerge: (_target, source) => source
469
- }
470
- )
471
- },
472
- getChooseVideoOpts() {
473
- return this.$pi.lang.mergeDeep(
474
- uploadImg.chooseVideoOpts,
475
- this.chooseVideoOpts,
476
- {
477
- arrayMerge: (_target, source) => source
478
- }
479
- )
480
- },
481
- getUploadMaxCount() {
482
- const maxCount = parseInt(this.maxCount, 10)
483
- return maxCount - this.getImgs.length
484
- },
485
- getCropMaskBackground() {
486
- return 'rgba(0, 0, 0, .3)'
487
- },
488
- getCropOption() {
489
- return this.$pi.lang.mergeDeep(uploadImg.cropOption, this.cropOption)
490
- },
491
- getExtension() {
492
- let extension = []
493
- if (this.type === 'image') {
494
- extension = this.getChooseImageOpts.extension || []
495
- } else if (this.type === 'video') {
496
- extension = this.getChooseVideoOpts.extension || []
497
- } else {
498
- // all
499
- extension = [
500
- ...this.getChooseFileOpts.extension,
501
- ...(this.fileTypes.includes('image')
502
- ? this.getChooseImageOpts.extension
503
- : []),
504
- ...(this.fileTypes.includes('video')
505
- ? this.getChooseVideoOpts.extension
506
- : [])
507
- ]
508
- }
509
- return extension?.filter(ext => !!ext)
510
- }
511
- },
512
- methods: {
513
- isImageFilename,
514
- isVideoFilename,
515
- getFileType(file) {
516
- if (!file) return ''
517
- const ext = file.split('.').pop()
518
- return ext.toLocaleUpperCase()
519
- },
520
- isRightType(selectFile) {
521
- const isRightType = this.getExtension.some(ext =>
522
- selectFile.name.endsWith(ext)
523
- )
524
- console.log(
525
- TAG,
526
- '当前文件扩展名配置为:',
527
- this.getExtension,
528
- '当前选择文件:',
529
- selectFile.name,
530
- '是否符合:',
531
- isRightType
532
- )
533
- if (!isRightType) {
534
- this.$toast(`请选择${this.getExtension.join('/')}文件上传`)
535
- }
536
- return isRightType
537
- },
538
- async handleDelete(index) {
539
- let val = null
540
- const beforeRemove = this.beforeRemove[PI_DEFAULT_FN_FLAG]
541
- ? this.beforeRemove.fn
542
- : this.beforeRemove
543
- if (this.$pi.lang.isFunction(beforeRemove)) {
544
- // 删除之前的钩子, 如果定义了则使用钩子删除文件
545
- val = await beforeRemove(index)
546
- } else {
547
- val = this.isValString ? '' : this.val.filter((_, i) => i !== index)
548
- }
549
- this.$emit('remove', index)
550
- this.val = val
551
- this.handleEmitChange()
552
- },
553
- handlePreview(img) {
554
- const file = this.imgField ? img[this.imgField] : img
555
- if (isImageFilename(file)) {
556
- this.handlePreviewImage(file)
557
- return
558
- }
559
- if (isVideoFilename(file)) {
560
- this.$emit('previewVideo', file)
561
- return
562
- }
563
- // 文件预览
564
- uni.downloadFile({
565
- url: file,
566
- success: res => {
567
- const filePath = res.tempFilePath
568
- // fileType 文件类型,指定文件类型打开文件,有效值 doc, xls, ppt, pdf, docx, xlsx, pptx,支付宝小程序仅支持pdf
569
- // 支付宝小程序必填,其他平台非必填
570
- uni.openDocument({
571
- filePath,
572
- complete: res => {
573
- console.log('文件预览', res)
574
- }
575
- })
576
- }
577
- })
578
- },
579
- // 预览图片
580
- handlePreviewImage(img) {
581
- if (!this.previewFullImage) return
582
- let urls = []
583
- let current = ''
584
-
585
- if (this.isValString) {
586
- current = this.val
587
- urls = [this.val]
588
- } else {
589
- urls = this.imgField
590
- ? this.val.map(img => img[this.imgField])
591
- : this.val
592
- current = img
593
- }
594
-
595
- // 过滤出图片类型的文件
596
- urls = urls.filter(url => isImageFilename(url))
597
-
598
- // eslint-disable-next-line no-undef
599
- uni.previewImage({
600
- urls,
601
- current,
602
- indicator: 'default',
603
- success: () => {
604
- this.$emit('preview', current, urls)
605
- }
606
- })
607
- },
608
- async handleUpload(paths) {
609
- const beforeUpload = this.beforeUpload[PI_DEFAULT_FN_FLAG]
610
- ? this.beforeUpload.fn
611
- : this.beforeUpload
612
- const onProgress = this.onProgress[PI_DEFAULT_FN_FLAG]
613
- ? this.onProgress.fn
614
- : this.onProgress
615
- const parseResultFn = this.parseResultFn[PI_DEFAULT_FN_FLAG]
616
- ? this.parseResultFn.fn
617
- : this.parseResultFn
618
- try {
619
- for await (const filePath of paths) {
620
- // ---------- 上传之前的钩子 ----------
621
- const file = filePath
622
-
623
- let beforeUploadResult = true
624
- if (this.$pi.lang.isFunction(beforeUpload)) {
625
- console.log(TAG, '调用文件上传前钩子')
626
- beforeUploadResult = await beforeUpload(file)
627
- }
628
- if (!beforeUploadResult) {
629
- console.log(TAG, '文件上传前钩子返回false,跳过上传')
630
- continue
631
- }
632
-
633
- // ---------- 上传文件 ----------
634
-
635
- let uploadResult = null
636
- const params = {
637
- url: this.action,
638
- filePath: file,
639
- name: this.name,
640
- formData: this.formData,
641
- header: this.headers
642
- }
643
- if (this.$pi.lang.isFunction(onProgress)) {
644
- console.log(TAG, '使用自定义上传函数')
645
- // 上传之前的钩子, 如果定义了则使用钩子上传文件
646
- uploadResult = await onProgress(params)
647
- } else {
648
- const [, uploadFileResult] = await uni.uploadFile(params)
649
- uploadResult = uploadFileResult
650
- }
651
- console.log(TAG, '上传文件结果', uploadResult)
652
-
653
- // ---------- 解析上传结果 ----------
654
- this.$emit('uploaded', uploadResult)
655
- const item = await parseResultFn(uploadResult)
656
- if (item) {
657
- this.isValString ? (this.val = item) : this.val.push(item)
658
- this.handleEmitChange()
659
- }
660
- }
661
- } catch (e) {
662
- console.log(TAG, '上传文件失败', e)
663
- this.$emit('fail', e)
664
- }
665
- },
666
- handleCrop(res) {
667
- console.log(TAG, '处理剪裁')
668
- this.$emit('crop', res.img)
669
- this.cropedPic = res.img
670
- },
671
- handleCancelCrop() {
672
- console.log(TAG, '取消剪裁')
673
- this.$emit('cancelCrop')
674
- this.showCrop = false
675
- this.cropPic = ''
676
- },
677
- handleCompelteCrop() {
678
- console.log(TAG, '完成剪裁')
679
- this.$emit('croped', [this.cropedPic])
680
- this.showCrop = false
681
- this.handleUpload([this.cropedPic])
682
- },
683
- async handleCompressImgs(tempFilePaths) {
684
- const compressUrls = []
685
-
686
- for (let index = 0; index < tempFilePaths.length; index++) {
687
- const url = tempFilePaths[index]
688
- const [, result] = await uni.compressImage({
689
- src: url,
690
- ...this.compressOption
691
- })
692
- const { errMsg, tempFilePath } = result
693
- if (
694
- errMsg == 'compressImage:ok' &&
695
- tempFilePath &&
696
- typeof tempFilePath == 'string'
697
- ) {
698
- compressUrls.push(tempFilePath)
699
- console.log(TAG, '压缩图片成功', tempFilePath, 'src=' + url)
700
- } else {
701
- compressUrls.push(url)
702
- console.log(TAG, '压缩图片成功', tempFilePath, 'src=' + url)
703
- }
704
- }
705
- return compressUrls
706
- },
707
- handleChoose() {
708
- if (this.disabled || !this.getUploadMaxCount) return
709
- // 检查上传地址
710
- const onProgress = this.onProgress[PI_DEFAULT_FN_FLAG]
711
- ? this.onProgress.fn
712
- : this.onProgress
713
- if (!onProgress && !this.action) {
714
- this.$toast('请配置上传地址')
715
- return
716
- }
717
- if (this.$pi.lang.isEmpty(this.headers)) {
718
- console.log(TAG, '当前图片上传headers为空,请检查是否需要配置授权信息')
719
- }
720
- console.log('当前上传文件类型累:', this.type)
721
- if (this.type === 'all') {
722
- // #ifndef MP-WEIXIN
723
- this.handleChooseFile()
724
- // #endif
725
-
726
- // #ifdef MP-WEIXIN
727
- const { fromWxMessage } = this.getChooseFileOpts
728
- if (fromWxMessage) {
729
- this.showActionSheet = true
730
- } else {
731
- this.handleChooseMedia()
732
- }
733
- // #endif
734
-
735
- return
736
- }
737
- if (this.type === 'image') {
738
- this.handleChooseImage()
739
- return
740
- }
741
- if (this.type === 'video') {
742
- // #ifndef MP-WEIXIN
743
- this.handleChooseVideo()
744
- // #endif
745
-
746
- // #ifdef MP-WEIXIN
747
- this.handleChooseMedia()
748
- // #endif
749
-
750
- return
751
- }
752
- },
753
- async handleChooseFile() {
754
- const { sizeType, sourceType, crop } = this.getChooseFileOpts
755
- try {
756
- const [, result] = await uni.chooseFile({
757
- count: this.getUploadMaxCount,
758
- sizeType,
759
- sourceType,
760
- crop
761
- })
762
- let { errMsg, tempFiles } = result
763
- console.log(TAG, '上传文件结果', result)
764
- if (errMsg !== 'chooseFile:ok') {
765
- throw new Error(errMsg)
766
- }
767
- this.handleUpload(tempFiles)
768
- } catch (error) {
769
- console.log(TAG, '上传文件失败', error)
770
- this.$emit('fail', error)
771
- }
772
- },
773
- // 从微信聊天会话中选择文件
774
- async handleSelectMessageFile() {
775
- // #ifndef MP-WEIXIN
776
- this.$toast('请在微信小程序中使用')
777
- // #endif
778
-
779
- console.log('从微信聊天会话中选择文件')
780
-
781
- // #ifdef MP-WEIXIN
782
- this.showSheet = false
783
- try {
784
- const [, result] = await uni.chooseMessageFile({
785
- count: this.getUploadMaxCount,
786
- type:
787
- this.fileTypes.includes('video') || this.fileTypes.includes('video')
788
- ? 'all'
789
- : 'file'
790
- })
791
- if (!result) {
792
- return
793
- }
794
- let { errMsg, tempFiles } = result
795
- console.log(TAG, '选择微信聊天记录文件', result)
796
- if (errMsg !== 'chooseMessageFile:ok') {
797
- throw new Error(errMsg)
798
- }
799
- // chooseMessageFile 没有扩展名限制,这里自己做过滤
800
- tempFiles = tempFiles.filter(file => {
801
- return this.isRightType(file)
802
- })
803
- console.log(TAG, '过滤后的文件列表:', tempFiles)
804
- this.handleUpload(tempFiles)
805
- } catch (error) {
806
- console.log(error)
807
- }
808
- // #endif
809
- },
810
- async handleChooseImage() {
811
- const { sizeType, sourceType, crop } = this.getChooseImageOpts
812
- try {
813
- const [, result] = await uni.chooseImage({
814
- count: this.getUploadMaxCount,
815
- sizeType,
816
- sourceType,
817
- crop
818
- })
819
- let { errMsg, tempFilePaths } = result
820
- if (errMsg !== 'chooseImage:ok') {
821
- throw new Error(errMsg)
822
- }
823
- // #ifndef H5
824
- // 压缩图片
825
- if (
826
- this.compressOption &&
827
- this.$pi.system.systemInfo.platform !== 'devtools'
828
- ) {
829
- tempFilePaths = await this.handleCompressImgs(tempFilePaths)
830
- }
831
- // #endif
832
- if (
833
- this.getUploadMaxCount === 1 &&
834
- this.crop &&
835
- tempFilePaths.length === 1
836
- ) {
837
- // 单张图片设置了剪裁
838
- this.showCrop = true
839
- this.cropPic = tempFilePaths[0]
840
- return
841
- }
842
- this.handleUpload(tempFilePaths)
843
- } catch (error) {
844
- console.log(TAG, '上传文件失败', error)
845
- this.$emit('fail', error)
846
- }
847
- },
848
- async handleChooseVideo() {
849
- const { sourceType, maxDuration, camera } = this.getChooseVideoOpts
850
- try {
851
- const [, result] = await uni.chooseVideo({
852
- sourceType,
853
- maxDuration,
854
- camera
855
- })
856
- let { errMsg, tempFilePath, tempFile } = result
857
- if (errMsg !== 'chooseVideo:ok') {
858
- throw new Error(errMsg)
859
- }
860
- tempFile.path = tempFilePath
861
- console.log(TAG, '上传视频结果', result)
862
- this.handleUpload([tempFile])
863
- } catch (error) {
864
- console.log(TAG, '上传视频失败', error)
865
- this.$emit('fail', error)
866
- }
867
- },
868
- async handleChooseMedia() {
869
- const { sourceType, maxDuration, camera } =
870
- this.type === 'video' ? this.getChooseVideoOpts : this.getChooseFileOpts
871
- try {
872
- const [, result] = await uni.chooseMedia({
873
- count: this.getUploadMaxCount,
874
- mediaType: this.type === 'video' ? ['video'] : ['mix'],
875
- extension: this.getExtension,
876
- sourceType,
877
- maxDuration,
878
- camera
879
- })
880
- let { errMsg, tempFiles } = result
881
- if (errMsg !== 'chooseMedia:ok') {
882
- throw new Error(errMsg)
883
- }
884
- console.log(TAG, '上传媒体结果', result)
885
-
886
- // #ifndef H5
887
- // 非H5端/开发者工具,上传视频,执行压缩视频操作
888
- if (this.$pi.system.systemInfo.platform !== 'devtools') {
889
- const compressTempFiles = []
890
- for await (const tempFile of tempFiles) {
891
- const tempFilePath = tempFile.tempFilePath
892
- let filePath = ''
893
- if (isImageFilename(tempFilePath)) {
894
- const filePaths = await this.handleCompressImgs([
895
- tempFile.tempFilePath
896
- ])
897
- filePath = filePaths[0]
898
- } else {
899
- filePath = await this.handleCompressVideo(tempFile.tempFilePath)
900
- }
901
-
902
- compressTempFiles.push(filePath)
903
- }
904
- this.handleUpload(compressTempFiles)
905
- return
906
- }
907
- // #endif
908
-
909
- this.handleUpload(tempFiles.map(file => file.tempFilePath))
910
- } catch (error) {
911
- console.log(TAG, '上传视频失败', error)
912
- this.$emit('fail', error)
913
- }
914
- },
915
- // 压缩视频接口
916
- async handleCompressVideo(tempUrl) {
917
- console.log('视频压缩中')
918
- uni.showLoading({
919
- title: '视频压缩中...'
920
- })
921
- const [, result] = await uni.compressVideo({
922
- src: tempUrl,
923
- quality: 'high' // 压缩质量 支持low, medium, high
924
- })
925
- uni.hideLoading()
926
- const { errMsg, tempFilePath } = result
927
- if (errMsg == 'compressVideo:ok') {
928
- return tempFilePath
929
- }
930
- return tempUrl
931
- },
932
- handleActionSheetSelect(type) {
933
- if (type.id === 1) {
934
- this.handleChooseMedia()
935
- } else {
936
- this.handleSelectMessageFile()
937
- }
938
- }
939
- }
940
- }
941
- </script>
942
-
943
- <style lang="scss" scoped>
944
- .pi-upload-img {
945
- display: flex;
946
- flex-wrap: wrap;
947
- .close {
948
- position: absolute;
949
- top: 0;
950
- right: 0;
951
- z-index: 1;
952
- display: flex;
953
- align-items: center;
954
- justify-content: center;
955
- width: 38rpx;
956
- height: 38rpx;
957
- font-weight: 500;
958
- background: #ffffff;
959
- border: 2px solid #ffffff;
960
- border-radius: 50%;
961
- transform: translate(40%, -40%);
962
- }
963
- & > view {
964
- margin-right: 24rpx;
965
- margin-bottom: 24rpx;
966
- }
967
- .file-mask {
968
- position: absolute;
969
- top: 0;
970
- left: 0;
971
- width: 100%;
972
- height: 100%;
973
- display: flex;
974
- flex-direction: column;
975
- align-items: center;
976
- justify-content: center;
977
- background: rgba(0, 0, 0, 0.3);
978
- }
979
- }
980
- </style>
1
+ <!--
2
+ * @Author: zhangzhenfei
3
+ * @Date: 2021-08-13 11:31:57
4
+ * @LastEditTime: 2024-06-11 11:39:08
5
+ * @LastEditors: zhangzhenfei
6
+ * @Description: 图片上传组件
7
+ * @FilePath: /piui-awesome/src/piui/components/pi-upload-img/index.vue
8
+ -->
9
+
10
+ <template>
11
+ <view
12
+ class="pi-upload-img"
13
+ :style="[customStyle]"
14
+ :class="[customClass, { 'pi-pd-top-12': !getDisabled }]"
15
+ >
16
+ <!-- 已上传图片展示 -->
17
+ <view
18
+ v-for="(img, index) in getImgs"
19
+ :key="index"
20
+ class="pi-rela pi-flex-column-center"
21
+ @tap="handlePreview(img)"
22
+ >
23
+ <view v-if="!getDisabled" class="close" @tap.stop="handleDelete(index)">
24
+ <pi-icon name="roundclosefill" color="#8e8e8e" size="36" />
25
+ </view>
26
+ <image
27
+ v-if="isImageFilename(imgField ? img[imgField] : img)"
28
+ :style="[getItemStyle]"
29
+ class="pi-of-hidden"
30
+ :mode="imageMode"
31
+ :src="imgField ? img[imgField] : img"
32
+ />
33
+ <view
34
+ v-else
35
+ class="pi-rela pi-of-hidden pi-radius-8"
36
+ :style="[getItemStyle]"
37
+ >
38
+ <view class="file-mask">
39
+ <pi-icon
40
+ :name="
41
+ isVideoFilename(imgField ? img[imgField] : img)
42
+ ? 'videofill'
43
+ : 'activity-fill'
44
+ "
45
+ size="48"
46
+ color="#0C6DF4"
47
+ />
48
+ <view class="pi-mg-top-12 pi-fz-22">
49
+ {{ getFileType(imgField ? img[imgField] : img) }}
50
+ </view>
51
+ </view>
52
+ </view>
53
+ </view>
54
+ <!-- 上传框 -->
55
+ <view v-if="getUploadMaxCount && !getDisabled">
56
+ <view
57
+ :style="[getUploadBtnStyle]"
58
+ class="pi-flex-column-center"
59
+ @tap="handleChoose"
60
+ >
61
+ <slot name="uploadBtn">
62
+ <!-- 添加按钮 -->
63
+ <pi-icon
64
+ :custom-style="getUploadIcon.customStyle"
65
+ :custom-class="getUploadIcon.customClass"
66
+ :name="getUploadIcon.name"
67
+ :dot="getUploadIcon.dot"
68
+ :dot-radius="getUploadIcon.dotRadius"
69
+ :badge="getUploadIcon.badge"
70
+ :color="getUploadIcon.color"
71
+ :size="getUploadIcon.size"
72
+ :class-prefix="getUploadIcon.classPrefix"
73
+ />
74
+ </slot>
75
+ <view v-if="uploadText" class="pi-mg-top-6 pi-fz-24 pi-light-gray">{{
76
+ uploadText
77
+ }}</view>
78
+ </view>
79
+ </view>
80
+ <!-- 剪裁弹窗 -->
81
+ <pi-mask
82
+ v-model="showCrop"
83
+ :mask-closeable="false"
84
+ background="rgba(0, 0, 0, .9)"
85
+ >
86
+ <view class="pi-abso-full pi-flex-column">
87
+ <view class="pi-flex-sub">
88
+ <pi-img-cropper
89
+ :custom-style="getCropOption.customStyle"
90
+ :custom-class="getCropOption.customClass"
91
+ :src="cropPic"
92
+ :file-type="getCropOption.fileType"
93
+ :quality="getCropOption.quality"
94
+ :crop-size="getCropOption.cropSize"
95
+ :min-crop-size="getCropOption.minCropSize"
96
+ :boundary-detect="getCropOption.boundaryDetect"
97
+ :keep-crop-ratio="getCropOption.keepCropRatio"
98
+ :disable-rotate="getCropOption.disableRotate"
99
+ :canvas-zoom="getCropOption.canvasZoom"
100
+ :mask-background="getCropMaskBackground"
101
+ @cropped="handleCrop"
102
+ />
103
+ </view>
104
+ <pi-bottom-bar
105
+ border-top="none"
106
+ :background="getCropMaskBackground"
107
+ :safe-area-bg-color="getCropMaskBackground"
108
+ >
109
+ <view
110
+ class="pi-justify-between pi-align-center pi-pd-tb-32 pi-pd-lr-24 pi-fz-32"
111
+ >
112
+ <view class="pi-white" @tap="handleCancelCrop">取消</view>
113
+ <view class="pi-primary" @tap="handleCompelteCrop">完成</view>
114
+ </view>
115
+ </pi-bottom-bar>
116
+ </view>
117
+ </pi-mask>
118
+ <!-- 上传视频操作面板(小程序专用) -->
119
+ <pi-action-sheet
120
+ v-model="showActionSheet"
121
+ :items="actionSheetItems"
122
+ :popup="{
123
+ borderRadius: 0
124
+ }"
125
+ @select="handleActionSheetSelect"
126
+ />
127
+ </view>
128
+ </template>
129
+
130
+ <script>
131
+ /**
132
+ * 通过v-model控制蒙层是否显示
133
+ * input 蒙层显示或者关闭的时候触发事件 value: boolean (蒙层是否显示)
134
+ */
135
+ import ValueSync from '../../mixin/value-sync'
136
+ import { getConfig } from '../../config'
137
+
138
+ const TAG = 'PiUploadImg'
139
+ const { uploadImg } = getConfig()
140
+
141
+ const PI_DEFAULT_FN_FLAG = 'PI_DEFAULT_FN_FLAG'
142
+
143
+ function isImageFilename(filename) {
144
+ const imageExtensions = /\.(jpg|jpeg|png|gif|bmp|tiff|webp)$/i
145
+ return imageExtensions.test(filename)
146
+ }
147
+
148
+ function isVideoFilename(filename) {
149
+ const videoExtensions = /\.(mp4|avi|mov|wmv|mpg|flv|mkv)$/i
150
+ return videoExtensions.test(filename)
151
+ }
152
+
153
+ export default {
154
+ name: 'PiUploadImg',
155
+ // 混入v-model
156
+ mixins: [ValueSync],
157
+ props: {
158
+ // 初始值
159
+ value: {
160
+ required: false,
161
+ type: [Array, String],
162
+ default() {
163
+ return []
164
+ }
165
+ },
166
+ // 自定义样式
167
+ customStyle: {
168
+ type: Object,
169
+ default() {
170
+ // {}
171
+ return uploadImg.customStyle
172
+ }
173
+ },
174
+ // 自定义样式类
175
+ customClass: {
176
+ type: String,
177
+ default() {
178
+ // ''
179
+ return uploadImg.customClass
180
+ }
181
+ },
182
+ // 上传按钮样式
183
+ itemStyle: {
184
+ type: Object,
185
+ default() {
186
+ // {}
187
+ return uploadImg.itemStyle
188
+ }
189
+ },
190
+ // 上传按钮样式
191
+ uploadBtnStyle: {
192
+ type: Object,
193
+ default() {
194
+ // {}
195
+ return uploadImg.uploadBtnStyle
196
+ }
197
+ },
198
+ // 上传图片的字段名称,字符串形式(默认值:'')
199
+ imgField: {
200
+ type: String,
201
+ default() {
202
+ return uploadImg.imgField
203
+ }
204
+ },
205
+ // 显示的图片模式
206
+ imageMode: {
207
+ type: String,
208
+ default() {
209
+ // 'aspectFill'
210
+ return uploadImg.imageMode
211
+ }
212
+ },
213
+ // 上传接口地址,字符串形式(默认值:'')
214
+ action: {
215
+ type: String,
216
+ default() {
217
+ return uploadImg.action
218
+ }
219
+ },
220
+ // 请求头,对象形式(默认值:{})
221
+ headers: {
222
+ type: Object,
223
+ default() {
224
+ return uploadImg.headers
225
+ }
226
+ },
227
+ // 上传表单额外数据,对象形式(默认值:{})
228
+ formData: {
229
+ type: Object,
230
+ default() {
231
+ return uploadImg.formData
232
+ }
233
+ },
234
+ // 上传的文件字段名
235
+ name: {
236
+ type: String,
237
+ default() {
238
+ return uploadImg.name
239
+ }
240
+ },
241
+ // 上传区域尺寸(半径)
242
+ size: {
243
+ type: [String, Number],
244
+ default() {
245
+ // ''
246
+ return uploadImg.size
247
+ }
248
+ },
249
+ // 是否在点击预览图后展示全屏图片预览
250
+ previewFullImage: {
251
+ type: Boolean,
252
+ default() {
253
+ return uploadImg.previewFullImage
254
+ }
255
+ },
256
+ // 是否可以删除上传的文件
257
+ deletable: {
258
+ type: Boolean,
259
+ default() {
260
+ return uploadImg.deletable
261
+ }
262
+ },
263
+ // 是否禁用上传
264
+ disabled: {
265
+ type: Boolean,
266
+ default() {
267
+ return uploadImg.disabled
268
+ }
269
+ },
270
+ // 上传文件的最大数量
271
+ maxCount: {
272
+ type: [String, Number],
273
+ default() {
274
+ return uploadImg.maxCount
275
+ }
276
+ },
277
+ // 上传区域文字提示
278
+ uploadText: {
279
+ type: String,
280
+ default() {
281
+ return uploadImg.uploadText
282
+ }
283
+ },
284
+ // 上传区域图标
285
+ uploadIcon: {
286
+ type: Object,
287
+ default() {
288
+ return uploadImg.uploadIcon
289
+ }
290
+ },
291
+ // 当maxCount设置为1的时候,且type为‘image’,可开启裁剪
292
+ crop: {
293
+ type: Boolean,
294
+ // `false`
295
+ default: uploadImg.crop
296
+ },
297
+ // 裁剪参数
298
+ cropOption: {
299
+ type: Object,
300
+ default() {
301
+ return uploadImg.cropOption
302
+ }
303
+ },
304
+ // 上传成功解析对象方法
305
+ parseResultFn: {
306
+ type: [Object, Function],
307
+ default() {
308
+ return {
309
+ [PI_DEFAULT_FN_FLAG]: true,
310
+ fn: uploadImg.parseResultFn
311
+ }
312
+ }
313
+ },
314
+ // 上传之前的钩子
315
+ beforeUpload: {
316
+ type: [Object, Function],
317
+ default() {
318
+ return {
319
+ [PI_DEFAULT_FN_FLAG]: true,
320
+ fn: uploadImg.beforeUpload
321
+ }
322
+ }
323
+ },
324
+ // 文件上传时的钩子
325
+ onProgress: {
326
+ type: [Object, Function],
327
+ default() {
328
+ return {
329
+ [PI_DEFAULT_FN_FLAG]: true,
330
+ fn: uploadImg.onProgress
331
+ }
332
+ }
333
+ },
334
+ // 删除之前的钩子
335
+ beforeRemove: {
336
+ type: [Object, Function],
337
+ default() {
338
+ return {
339
+ [PI_DEFAULT_FN_FLAG]: true,
340
+ fn: uploadImg.beforeRemove
341
+ }
342
+ }
343
+ },
344
+ // 压缩参数
345
+ compressOption: {
346
+ type: Object,
347
+ default() {
348
+ return uploadImg.compressOption
349
+ }
350
+ },
351
+ // 文件类型
352
+ type: {
353
+ type: String,
354
+ default() {
355
+ return uploadImg.type // 'all', 'image', 'video'
356
+ }
357
+ },
358
+ // 当 type 为 all 时生效,允许上传的文件类型是否包含 video 和 image
359
+ fileTypes: {
360
+ type: Array,
361
+ default() {
362
+ return uploadImg.fileTypes
363
+ }
364
+ },
365
+ // 当type为 "all"时生效,调用uni.chooseFile参数
366
+ chooseFileOpts: {
367
+ type: Object,
368
+ default() {
369
+ return uploadImg.chooseFileOpts
370
+ }
371
+ },
372
+ // 当type为 "image"时生效,调用uni.chooseImage参数
373
+ chooseImageOpts: {
374
+ type: Object,
375
+ default() {
376
+ return uploadImg.chooseImageOpts
377
+ }
378
+ },
379
+ // 当type为 "video"时生效,调用uniapp.chooseVideo参数
380
+ chooseVideoOpts: {
381
+ type: Object,
382
+ default() {
383
+ return uploadImg.chooseVideoOpts
384
+ }
385
+ }
386
+ },
387
+ data() {
388
+ return {
389
+ showCrop: false, // 是否显示裁剪工具
390
+ cropPic: '', // 需要剪裁的图片
391
+ cropedPic: '', // 剪裁后的图片
392
+ showActionSheet: false // 是否显示上传视频操作面板
393
+ }
394
+ },
395
+ computed: {
396
+ getDisabled() {
397
+ const parent = this.$pi.parent(this, 'PiFormItem')
398
+ return this.disabled || (parent && parent.getDisabled)
399
+ },
400
+ actionSheetItems() {
401
+ return [
402
+ {
403
+ id: 1,
404
+ text: '选择媒体图片/视频'
405
+ },
406
+ {
407
+ id: 2,
408
+ text: '选择微信聊天文件'
409
+ }
410
+ ]
411
+ },
412
+ isValString() {
413
+ return this.$pi.lang.isString(this.val)
414
+ },
415
+ getImgs() {
416
+ if (this.val === null || this.val === undefined) {
417
+ return []
418
+ }
419
+ return this.isValString
420
+ ? this.val
421
+ ? [this.val]
422
+ : []
423
+ : this.val.filter(img => img)
424
+ },
425
+ getItemStyle() {
426
+ const style = {
427
+ width: this.getSize,
428
+ height: this.getSize
429
+ }
430
+ const uploadStyle = this.$pi.lang.mergeDeep(
431
+ uploadImg.itemStyle,
432
+ this.itemStyle
433
+ )
434
+ return this.$pi.lang.mergeDeep(style, uploadStyle)
435
+ },
436
+ getSize() {
437
+ return this.$pi.common.addUnit(this.size)
438
+ },
439
+ getUploadBtnStyle() {
440
+ const style = {
441
+ width: this.getSize,
442
+ height: this.getSize
443
+ }
444
+ const uploadBtnStyle = this.$pi.lang.mergeDeep(
445
+ uploadImg.uploadBtnStyle,
446
+ this.uploadBtnStyle
447
+ )
448
+ return this.$pi.lang.mergeDeep(style, uploadBtnStyle)
449
+ },
450
+ getUploadIcon() {
451
+ return this.$pi.lang.mergeDeep(uploadImg.uploadIcon, this.uploadIcon)
452
+ },
453
+ getChooseImageOpts() {
454
+ // 以覆盖的方式合并数组
455
+ return this.$pi.lang.mergeDeep(
456
+ uploadImg.chooseImageOpts,
457
+ this.chooseImageOpts,
458
+ {
459
+ arrayMerge: (_target, source) => source
460
+ }
461
+ )
462
+ },
463
+ getChooseFileOpts() {
464
+ return this.$pi.lang.mergeDeep(
465
+ uploadImg.chooseFileOpts,
466
+ this.chooseFileOpts,
467
+ {
468
+ arrayMerge: (_target, source) => source
469
+ }
470
+ )
471
+ },
472
+ getChooseVideoOpts() {
473
+ return this.$pi.lang.mergeDeep(
474
+ uploadImg.chooseVideoOpts,
475
+ this.chooseVideoOpts,
476
+ {
477
+ arrayMerge: (_target, source) => source
478
+ }
479
+ )
480
+ },
481
+ getUploadMaxCount() {
482
+ const maxCount = parseInt(this.maxCount, 10)
483
+ return maxCount - this.getImgs.length
484
+ },
485
+ getCropMaskBackground() {
486
+ return 'rgba(0, 0, 0, .3)'
487
+ },
488
+ getCropOption() {
489
+ return this.$pi.lang.mergeDeep(uploadImg.cropOption, this.cropOption)
490
+ },
491
+ getExtension() {
492
+ let extension = []
493
+ if (this.type === 'image') {
494
+ extension = this.getChooseImageOpts.extension || []
495
+ } else if (this.type === 'video') {
496
+ extension = this.getChooseVideoOpts.extension || []
497
+ } else {
498
+ // all
499
+ extension = [
500
+ ...this.getChooseFileOpts.extension,
501
+ ...(this.fileTypes.includes('image')
502
+ ? this.getChooseImageOpts.extension
503
+ : []),
504
+ ...(this.fileTypes.includes('video')
505
+ ? this.getChooseVideoOpts.extension
506
+ : [])
507
+ ]
508
+ }
509
+ return extension?.filter(ext => !!ext)
510
+ }
511
+ },
512
+ methods: {
513
+ isImageFilename,
514
+ isVideoFilename,
515
+ getFileType(file) {
516
+ if (!file) return ''
517
+ const ext = file.split('.').pop()
518
+ return ext.toLocaleUpperCase()
519
+ },
520
+ isRightType(selectFile) {
521
+ const isRightType = this.getExtension.some(ext =>
522
+ selectFile.name.endsWith(ext)
523
+ )
524
+ console.log(
525
+ TAG,
526
+ '当前文件扩展名配置为:',
527
+ this.getExtension,
528
+ '当前选择文件:',
529
+ selectFile.name,
530
+ '是否符合:',
531
+ isRightType
532
+ )
533
+ if (!isRightType) {
534
+ this.$toast(`请选择${this.getExtension.join('/')}文件上传`)
535
+ }
536
+ return isRightType
537
+ },
538
+ async handleDelete(index) {
539
+ let val = null
540
+ const beforeRemove = this.beforeRemove[PI_DEFAULT_FN_FLAG]
541
+ ? this.beforeRemove.fn
542
+ : this.beforeRemove
543
+ if (this.$pi.lang.isFunction(beforeRemove)) {
544
+ // 删除之前的钩子, 如果定义了则使用钩子删除文件
545
+ val = await beforeRemove(index)
546
+ } else {
547
+ val = this.isValString ? '' : this.val.filter((_, i) => i !== index)
548
+ }
549
+ this.$emit('remove', index)
550
+ this.val = val
551
+ this.handleEmitChange()
552
+ },
553
+ handlePreview(img) {
554
+ const file = this.imgField ? img[this.imgField] : img
555
+ if (isImageFilename(file)) {
556
+ this.handlePreviewImage(file)
557
+ return
558
+ }
559
+ if (isVideoFilename(file)) {
560
+ this.$emit('previewVideo', file)
561
+ return
562
+ }
563
+ // 文件预览
564
+ uni.downloadFile({
565
+ url: file,
566
+ success: res => {
567
+ const filePath = res.tempFilePath
568
+ // fileType 文件类型,指定文件类型打开文件,有效值 doc, xls, ppt, pdf, docx, xlsx, pptx,支付宝小程序仅支持pdf
569
+ // 支付宝小程序必填,其他平台非必填
570
+ uni.openDocument({
571
+ filePath,
572
+ complete: res => {
573
+ console.log('文件预览', res)
574
+ }
575
+ })
576
+ }
577
+ })
578
+ },
579
+ // 预览图片
580
+ handlePreviewImage(img) {
581
+ if (!this.previewFullImage) return
582
+ let urls = []
583
+ let current = ''
584
+
585
+ if (this.isValString) {
586
+ current = this.val
587
+ urls = [this.val]
588
+ } else {
589
+ urls = this.imgField
590
+ ? this.val.map(img => img[this.imgField])
591
+ : this.val
592
+ current = img
593
+ }
594
+
595
+ // 过滤出图片类型的文件
596
+ urls = urls.filter(url => isImageFilename(url))
597
+
598
+ // eslint-disable-next-line no-undef
599
+ uni.previewImage({
600
+ urls,
601
+ current,
602
+ indicator: 'default',
603
+ success: () => {
604
+ this.$emit('preview', current, urls)
605
+ }
606
+ })
607
+ },
608
+ async handleUpload(paths) {
609
+ const beforeUpload = this.beforeUpload[PI_DEFAULT_FN_FLAG]
610
+ ? this.beforeUpload.fn
611
+ : this.beforeUpload
612
+ const onProgress = this.onProgress[PI_DEFAULT_FN_FLAG]
613
+ ? this.onProgress.fn
614
+ : this.onProgress
615
+ const parseResultFn = this.parseResultFn[PI_DEFAULT_FN_FLAG]
616
+ ? this.parseResultFn.fn
617
+ : this.parseResultFn
618
+ try {
619
+ for await (const filePath of paths) {
620
+ // ---------- 上传之前的钩子 ----------
621
+ const file = filePath
622
+
623
+ let beforeUploadResult = true
624
+ if (this.$pi.lang.isFunction(beforeUpload)) {
625
+ console.log(TAG, '调用文件上传前钩子')
626
+ beforeUploadResult = await beforeUpload(file)
627
+ }
628
+ if (!beforeUploadResult) {
629
+ console.log(TAG, '文件上传前钩子返回false,跳过上传')
630
+ continue
631
+ }
632
+
633
+ // ---------- 上传文件 ----------
634
+
635
+ let uploadResult = null
636
+ const params = {
637
+ url: this.action,
638
+ filePath: file,
639
+ name: this.name,
640
+ formData: this.formData,
641
+ header: this.headers
642
+ }
643
+ if (this.$pi.lang.isFunction(onProgress)) {
644
+ console.log(TAG, '使用自定义上传函数')
645
+ // 上传之前的钩子, 如果定义了则使用钩子上传文件
646
+ uploadResult = await onProgress(params)
647
+ } else {
648
+ const [, uploadFileResult] = await uni.uploadFile(params)
649
+ uploadResult = uploadFileResult
650
+ }
651
+ console.log(TAG, '上传文件结果', uploadResult)
652
+
653
+ // ---------- 解析上传结果 ----------
654
+ this.$emit('uploaded', uploadResult)
655
+ const item = await parseResultFn(uploadResult)
656
+ if (item) {
657
+ this.isValString ? (this.val = item) : this.val.push(item)
658
+ this.handleEmitChange()
659
+ }
660
+ }
661
+ } catch (e) {
662
+ console.log(TAG, '上传文件失败', e)
663
+ this.$emit('fail', e)
664
+ }
665
+ },
666
+ handleCrop(res) {
667
+ console.log(TAG, '处理剪裁')
668
+ this.$emit('crop', res.img)
669
+ this.cropedPic = res.img
670
+ },
671
+ handleCancelCrop() {
672
+ console.log(TAG, '取消剪裁')
673
+ this.$emit('cancelCrop')
674
+ this.showCrop = false
675
+ this.cropPic = ''
676
+ },
677
+ handleCompelteCrop() {
678
+ console.log(TAG, '完成剪裁')
679
+ this.$emit('croped', [this.cropedPic])
680
+ this.showCrop = false
681
+ this.handleUpload([this.cropedPic])
682
+ },
683
+ async handleCompressImgs(tempFilePaths) {
684
+ const compressUrls = []
685
+
686
+ for (let index = 0; index < tempFilePaths.length; index++) {
687
+ const url = tempFilePaths[index]
688
+ const [, result] = await uni.compressImage({
689
+ src: url,
690
+ ...this.compressOption
691
+ })
692
+ const { errMsg, tempFilePath } = result
693
+ if (
694
+ errMsg == 'compressImage:ok' &&
695
+ tempFilePath &&
696
+ typeof tempFilePath == 'string'
697
+ ) {
698
+ compressUrls.push(tempFilePath)
699
+ console.log(TAG, '压缩图片成功', tempFilePath, 'src=' + url)
700
+ } else {
701
+ compressUrls.push(url)
702
+ console.log(TAG, '压缩图片成功', tempFilePath, 'src=' + url)
703
+ }
704
+ }
705
+ return compressUrls
706
+ },
707
+ handleChoose() {
708
+ if (this.disabled || !this.getUploadMaxCount) return
709
+ // 检查上传地址
710
+ const onProgress = this.onProgress[PI_DEFAULT_FN_FLAG]
711
+ ? this.onProgress.fn
712
+ : this.onProgress
713
+ if (!onProgress && !this.action) {
714
+ this.$toast('请配置上传地址')
715
+ return
716
+ }
717
+ if (this.$pi.lang.isEmpty(this.headers)) {
718
+ console.log(TAG, '当前图片上传headers为空,请检查是否需要配置授权信息')
719
+ }
720
+ console.log('当前上传文件类型累:', this.type)
721
+ if (this.type === 'all') {
722
+ // #ifndef MP-WEIXIN
723
+ this.handleChooseFile()
724
+ // #endif
725
+
726
+ // #ifdef MP-WEIXIN
727
+ const { fromWxMessage } = this.getChooseFileOpts
728
+ if (fromWxMessage) {
729
+ this.showActionSheet = true
730
+ } else {
731
+ this.handleChooseMedia()
732
+ }
733
+ // #endif
734
+
735
+ return
736
+ }
737
+ if (this.type === 'image') {
738
+ this.handleChooseImage()
739
+ return
740
+ }
741
+ if (this.type === 'video') {
742
+ // #ifndef MP-WEIXIN
743
+ this.handleChooseVideo()
744
+ // #endif
745
+
746
+ // #ifdef MP-WEIXIN
747
+ this.handleChooseMedia()
748
+ // #endif
749
+
750
+ return
751
+ }
752
+ },
753
+ async handleChooseFile() {
754
+ const { sizeType, sourceType, crop } = this.getChooseFileOpts
755
+ try {
756
+ const [, result] = await uni.chooseFile({
757
+ count: this.getUploadMaxCount,
758
+ sizeType,
759
+ sourceType,
760
+ crop
761
+ })
762
+ let { errMsg, tempFiles } = result
763
+ console.log(TAG, '上传文件结果', result)
764
+ if (errMsg !== 'chooseFile:ok') {
765
+ throw new Error(errMsg)
766
+ }
767
+ this.handleUpload(tempFiles)
768
+ } catch (error) {
769
+ console.log(TAG, '上传文件失败', error)
770
+ this.$emit('fail', error)
771
+ }
772
+ },
773
+ // 从微信聊天会话中选择文件
774
+ async handleSelectMessageFile() {
775
+ // #ifndef MP-WEIXIN
776
+ this.$toast('请在微信小程序中使用')
777
+ // #endif
778
+
779
+ console.log('从微信聊天会话中选择文件')
780
+
781
+ // #ifdef MP-WEIXIN
782
+ this.showSheet = false
783
+ try {
784
+ const [, result] = await uni.chooseMessageFile({
785
+ count: this.getUploadMaxCount,
786
+ type:
787
+ this.fileTypes.includes('video') || this.fileTypes.includes('video')
788
+ ? 'all'
789
+ : 'file'
790
+ })
791
+ if (!result) {
792
+ return
793
+ }
794
+ let { errMsg, tempFiles } = result
795
+ console.log(TAG, '选择微信聊天记录文件', result)
796
+ if (errMsg !== 'chooseMessageFile:ok') {
797
+ throw new Error(errMsg)
798
+ }
799
+ // chooseMessageFile 没有扩展名限制,这里自己做过滤
800
+ tempFiles = tempFiles.filter(file => {
801
+ return this.isRightType(file)
802
+ })
803
+ console.log(TAG, '过滤后的文件列表:', tempFiles)
804
+ this.handleUpload(tempFiles)
805
+ } catch (error) {
806
+ console.log(error)
807
+ }
808
+ // #endif
809
+ },
810
+ async handleChooseImage() {
811
+ const { sizeType, sourceType, crop } = this.getChooseImageOpts
812
+ try {
813
+ const [, result] = await uni.chooseImage({
814
+ count: this.getUploadMaxCount,
815
+ sizeType,
816
+ sourceType,
817
+ crop
818
+ })
819
+ let { errMsg, tempFilePaths } = result
820
+ if (errMsg !== 'chooseImage:ok') {
821
+ throw new Error(errMsg)
822
+ }
823
+ // #ifndef H5
824
+ // 压缩图片
825
+ if (
826
+ this.compressOption &&
827
+ this.$pi.system.systemInfo.platform !== 'devtools'
828
+ ) {
829
+ tempFilePaths = await this.handleCompressImgs(tempFilePaths)
830
+ }
831
+ // #endif
832
+ if (
833
+ this.getUploadMaxCount === 1 &&
834
+ this.crop &&
835
+ tempFilePaths.length === 1
836
+ ) {
837
+ // 单张图片设置了剪裁
838
+ this.showCrop = true
839
+ this.cropPic = tempFilePaths[0]
840
+ return
841
+ }
842
+ this.handleUpload(tempFilePaths)
843
+ } catch (error) {
844
+ console.log(TAG, '上传文件失败', error)
845
+ this.$emit('fail', error)
846
+ }
847
+ },
848
+ async handleChooseVideo() {
849
+ const { sourceType, maxDuration, camera } = this.getChooseVideoOpts
850
+ try {
851
+ const [, result] = await uni.chooseVideo({
852
+ sourceType,
853
+ maxDuration,
854
+ camera
855
+ })
856
+ let { errMsg, tempFilePath, tempFile } = result
857
+ if (errMsg !== 'chooseVideo:ok') {
858
+ throw new Error(errMsg)
859
+ }
860
+ tempFile.path = tempFilePath
861
+ console.log(TAG, '上传视频结果', result)
862
+ this.handleUpload([tempFile])
863
+ } catch (error) {
864
+ console.log(TAG, '上传视频失败', error)
865
+ this.$emit('fail', error)
866
+ }
867
+ },
868
+ async handleChooseMedia() {
869
+ const { sourceType, maxDuration, camera } =
870
+ this.type === 'video' ? this.getChooseVideoOpts : this.getChooseFileOpts
871
+ try {
872
+ const [, result] = await uni.chooseMedia({
873
+ count: this.getUploadMaxCount,
874
+ mediaType: this.type === 'video' ? ['video'] : ['mix'],
875
+ extension: this.getExtension,
876
+ sourceType,
877
+ maxDuration,
878
+ camera
879
+ })
880
+ let { errMsg, tempFiles } = result
881
+ if (errMsg !== 'chooseMedia:ok') {
882
+ throw new Error(errMsg)
883
+ }
884
+ console.log(TAG, '上传媒体结果', result)
885
+
886
+ // #ifndef H5
887
+ // 非H5端/开发者工具,上传视频,执行压缩视频操作
888
+ if (this.$pi.system.systemInfo.platform !== 'devtools') {
889
+ const compressTempFiles = []
890
+ for await (const tempFile of tempFiles) {
891
+ const tempFilePath = tempFile.tempFilePath
892
+ let filePath = ''
893
+ if (isImageFilename(tempFilePath)) {
894
+ const filePaths = await this.handleCompressImgs([
895
+ tempFile.tempFilePath
896
+ ])
897
+ filePath = filePaths[0]
898
+ } else {
899
+ filePath = await this.handleCompressVideo(tempFile.tempFilePath)
900
+ }
901
+
902
+ compressTempFiles.push(filePath)
903
+ }
904
+ this.handleUpload(compressTempFiles)
905
+ return
906
+ }
907
+ // #endif
908
+
909
+ this.handleUpload(tempFiles.map(file => file.tempFilePath))
910
+ } catch (error) {
911
+ console.log(TAG, '上传视频失败', error)
912
+ this.$emit('fail', error)
913
+ }
914
+ },
915
+ // 压缩视频接口
916
+ async handleCompressVideo(tempUrl) {
917
+ console.log('视频压缩中')
918
+ uni.showLoading({
919
+ title: '视频压缩中...'
920
+ })
921
+ const [, result] = await uni.compressVideo({
922
+ src: tempUrl,
923
+ quality: 'high' // 压缩质量 支持low, medium, high
924
+ })
925
+ uni.hideLoading()
926
+ const { errMsg, tempFilePath } = result
927
+ if (errMsg == 'compressVideo:ok') {
928
+ return tempFilePath
929
+ }
930
+ return tempUrl
931
+ },
932
+ handleActionSheetSelect(type) {
933
+ if (type.id === 1) {
934
+ this.handleChooseMedia()
935
+ } else {
936
+ this.handleSelectMessageFile()
937
+ }
938
+ }
939
+ }
940
+ }
941
+ </script>
942
+
943
+ <style lang="scss" scoped>
944
+ .pi-upload-img {
945
+ display: flex;
946
+ flex-wrap: wrap;
947
+ .close {
948
+ position: absolute;
949
+ top: 0;
950
+ right: 0;
951
+ z-index: 1;
952
+ display: flex;
953
+ align-items: center;
954
+ justify-content: center;
955
+ width: 38rpx;
956
+ height: 38rpx;
957
+ font-weight: 500;
958
+ background: #ffffff;
959
+ border: 2px solid #ffffff;
960
+ border-radius: 50%;
961
+ transform: translate(40%, -40%);
962
+ }
963
+ & > view {
964
+ margin-right: 24rpx;
965
+ margin-bottom: 24rpx;
966
+ }
967
+ .file-mask {
968
+ position: absolute;
969
+ top: 0;
970
+ left: 0;
971
+ width: 100%;
972
+ height: 100%;
973
+ display: flex;
974
+ flex-direction: column;
975
+ align-items: center;
976
+ justify-content: center;
977
+ background: rgba(0, 0, 0, 0.3);
978
+ }
979
+ }
980
+ </style>