cwg-file-picker-wrapper.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. <template>
  2. <view class="file-picker-wrapper">
  3. <!-- 只读模式:仅展示 -->
  4. <view v-if="readonly" class="file-list readonly-list">
  5. <view v-for="(file, index) in innerFileList" :key="index" class="file-item readonly-item"
  6. @click="previewFile(file, index)">
  7. <image v-if="isImage(file)" :src="file.url || file.path" mode="aspectFill" class="file-thumb" />
  8. <view v-else class="file-icon" :class="getFileClass(file.name)">
  9. <text class="file-icon-text">{{ getFileIcon(file.name) }}</text>
  10. </view>
  11. <text class="file-name">{{ file.name }}</text>
  12. </view>
  13. <view v-if="!innerFileList.length" class="empty-text">暂无文件</view>
  14. </view>
  15. <!-- 正常模式:宫格上传(完全对齐官方 upload-image 样式) -->
  16. <view v-else class="uni-file-picker__container">
  17. <view class="file-picker__box" v-for="(item, index) in innerFileList" :key="index" :style="boxStyle">
  18. <view class="file-picker__box-content" :style="borderStyle">
  19. <!-- 图片 -->
  20. <image v-if="isImage(item)" class="file-image" :src="item.url || item.path" mode="aspectFill"
  21. @click.stop="previewFile(item, index)" />
  22. <!-- 视频 → 显示第一帧 + 播放图标 -->
  23. <view v-else-if="isVideo(item)" class="file-cover video-box" @click.stop="previewFile(item, index)">
  24. <image :src="item.url || item.path" class="file-image" mode="aspectFill" />
  25. <view class="video-play-icon">▶</view>
  26. </view>
  27. <!-- 其他文件(PDF/Word/Excel) -->
  28. <view v-else class="file-cover file-box" :class="getFileClass(item.name)"
  29. @click.stop="previewFile(item, index)">
  30. <text class="file-big-icon">{{ getFileIcon(item.name) }}</text>
  31. <text class="file-ext-name">{{ getFileExt(item.name) }}</text>
  32. </view>
  33. <!-- 删除 -->
  34. <view v-if="delIcon" class="icon-del-box" @click.stop="deleteFile(index)">
  35. <view class="icon-del"></view>
  36. <view class="icon-del rotate"></view>
  37. </view>
  38. <!-- 进度 -->
  39. <view v-if="item.status === 'uploading'" class="file-picker__progress">
  40. <progress class="file-picker__progress-item" :percent="item.progress" stroke-width="4"
  41. backgroundColor="#EBEBEB" />
  42. </view>
  43. <!-- 失败重试 -->
  44. <view v-if="item.status === 'error'" class="file-picker__mask" @click.stop="reUploadFile(index)">
  45. 点击重试
  46. </view>
  47. </view>
  48. </view>
  49. <!-- 添加按钮 -->
  50. <view v-if="innerFileList.length < limit" class="file-picker__box" :style="boxStyle">
  51. <view class="file-picker__box-content is-add" :style="borderStyle" @click="handleChoose">
  52. <cwg-icon name="icon_add" class="upload-icon" :size="24" />
  53. </view>
  54. </view>
  55. </view>
  56. </view>
  57. </template>
  58. <script setup>
  59. import { ref, watch, nextTick } from 'vue'
  60. import config from '@/config'
  61. import { userToken } from '@/composables/config'
  62. // === Vue3 v-model 标准写法 + 多类型兼容 ===
  63. const props = defineProps({
  64. modelValue: {
  65. type: [Array, String, Object],
  66. default: () => []
  67. },
  68. readonly: {
  69. type: Boolean,
  70. default: false
  71. },
  72. disabled: {
  73. type: Boolean,
  74. default: false
  75. },
  76. limit: {
  77. type: Number,
  78. default: 9
  79. },
  80. fileMediatype: {
  81. type: String,
  82. default: 'all'
  83. },
  84. delIcon: {
  85. type: Boolean,
  86. default: true
  87. },
  88. disablePreview: {
  89. type: Boolean,
  90. default: false
  91. },
  92. autoUpload: {
  93. type: Boolean,
  94. default: true
  95. },
  96. action: {
  97. type: String,
  98. default: ''
  99. },
  100. uploadUrl: {
  101. type: String,
  102. default: '/custom/bank/upload'
  103. },
  104. uploadHeaders: {
  105. type: Object,
  106. default: () => ({})
  107. },
  108. uploadName: {
  109. type: String,
  110. default: 'file'
  111. },
  112. uploadData: {
  113. type: Object,
  114. default: () => ({})
  115. },
  116. responseHandler: {
  117. type: Function,
  118. default: (res) => {
  119. try {
  120. const data = typeof res === 'string' ? JSON.parse(res) : res
  121. return {
  122. success: data.code === 200,
  123. path: data.data?.path || data.data,
  124. message: data.msg || '上传成功'
  125. }
  126. } catch (e) {
  127. return { success: false, message: '解析失败' }
  128. }
  129. }
  130. }
  131. })
  132. const emit = defineEmits([
  133. 'update:modelValue',
  134. 'change',
  135. 'delete',
  136. 'success',
  137. 'fail',
  138. 'progress',
  139. 'select'
  140. ])
  141. // 内部数据
  142. const innerFileList = ref([])
  143. const tempFileQueue = ref([])
  144. const originalType = ref('array') // 'string' | 'object' | 'array'
  145. const boxStyle = 'width:33.3%;height:0;padding-top:33.3%;'
  146. const borderStyle = 'border:1px #eee solid;border-radius:5px;'
  147. // ==============================================
  148. // 统一格式化函数(修复递归核心)
  149. // ==============================================
  150. function formatValue(val) {
  151. if (!val) return []
  152. // 字符串
  153. if (typeof val === 'string') {
  154. return [{
  155. path: val,
  156. url: val.startsWith('http') ? val : config.Host80 + val,
  157. name: val.split('/').pop(),
  158. status: 'success'
  159. }]
  160. }
  161. // 对象
  162. if (typeof val === 'object' && !Array.isArray(val)) {
  163. const path = val.path || val.url || ''
  164. return [{
  165. ...val,
  166. path,
  167. url: val.url || (path.startsWith('http') ? path : config.Host80 + path),
  168. name: val.name || path.split('/').pop(),
  169. status: 'success'
  170. }]
  171. }
  172. // 数组
  173. if (Array.isArray(val)) {
  174. return val.map(item => {
  175. if (typeof item === 'string') {
  176. return {
  177. path: item,
  178. url: item.startsWith('http') ? item : config.Host80 + item,
  179. name: item.split('/').pop(),
  180. status: 'success'
  181. }
  182. } else {
  183. const path = item?.path || item?.url || ''
  184. return {
  185. ...item,
  186. path,
  187. url: item?.url || (path.startsWith('http') ? path : config.Host80 + path),
  188. name: item?.name || path.split('/').pop(),
  189. status: 'success'
  190. }
  191. }
  192. })
  193. }
  194. return []
  195. }
  196. // ==============================================
  197. // 监听外部传入:防重复赋值 → 无递归
  198. // ==============================================
  199. watch(
  200. () => props.modelValue,
  201. (val) => {
  202. const formatted = formatValue(val)
  203. // 值相同不更新,防止死循环
  204. if (JSON.stringify(innerFileList.value) === JSON.stringify(formatted)) return
  205. if (!val) {
  206. innerFileList.value = []
  207. originalType.value = 'array'
  208. return
  209. }
  210. // 记录原始类型
  211. if (typeof val === 'string') originalType.value = 'string'
  212. else if (typeof val === 'object' && !Array.isArray(val)) originalType.value = 'object'
  213. else originalType.value = 'array'
  214. innerFileList.value = formatted
  215. },
  216. { immediate: true, deep: true }
  217. )
  218. // ==============================================
  219. // 内部变化同步外部:nextTick → 无递归
  220. // ==============================================
  221. watch(
  222. innerFileList,
  223. (list) => {
  224. nextTick(() => {
  225. let returnValue = []
  226. if (!list || list.length === 0) {
  227. returnValue = originalType.value === 'string' ? '' :
  228. originalType.value === 'object' ? {} : []
  229. emitUpdate(returnValue)
  230. return
  231. }
  232. // 只返回干净的 path 数据
  233. const cleanList = list.map(item => item.path || item.url || '')
  234. console.log(originalType);
  235. // 按原始类型返回
  236. if (props.limit === 1) {
  237. returnValue = cleanList[0] || ''
  238. } else if (originalType.value === 'string') returnValue = cleanList[0] || ''
  239. else if (originalType.value === 'object') returnValue = { path: cleanList[0] || '' }
  240. else returnValue = cleanList
  241. emitUpdate(returnValue)
  242. })
  243. },
  244. { deep: true }
  245. )
  246. // 统一触发更新
  247. function emitUpdate(val) {
  248. emit('update:modelValue', val)
  249. emit('change', val)
  250. }
  251. // ==============================================
  252. // 文件类型判断
  253. // ==============================================
  254. const isImage = (file) => {
  255. const ext = (file.path || file.name || '').split('.').pop()?.toLowerCase()
  256. return ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'].includes(ext)
  257. }
  258. const isVideo = (file) => {
  259. const ext = (file.path || file.name || '').split('.').pop()?.toLowerCase()
  260. return ['mp4', 'mov', 'avi', 'flv', 'wmv', 'rmvb'].includes(ext)
  261. }
  262. const getFileExt = (name) => {
  263. if (!name) return ''
  264. return name.split('.').pop()?.toUpperCase()
  265. }
  266. const getFileIcon = (name) => {
  267. const ext = getFileExt(name)
  268. if (ext === 'PDF') return 'PDF'
  269. if (['DOC', 'DOCX'].includes(ext)) return 'WORD'
  270. if (['XLS', 'XLSX'].includes(ext)) return 'EXCEL'
  271. if (isVideo({ name })) return '▶'
  272. if (isImage({ name })) return 'IMG'
  273. return 'FILE'
  274. }
  275. const getFileClass = (name) => {
  276. const ext = getFileExt(name)
  277. if (ext === 'PDF') return 'file-pdf'
  278. if (['DOC', 'DOCX'].includes(ext)) return 'file-word'
  279. if (['XLS', 'XLSX'].includes(ext)) return 'file-excel'
  280. if (isVideo({ name })) return 'file-video'
  281. return 'file-other'
  282. }
  283. // ==============================================
  284. // 预览
  285. // ==============================================
  286. const previewFile = (file, index) => {
  287. if (props.disablePreview || file.status === 'uploading' || file.status === 'error') return
  288. const url = file.url || file.path
  289. const name = file.name || '文件'
  290. if (isImage(file)) {
  291. const successImages = innerFileList.value.filter(item => isImage(item) && item.status === 'success')
  292. const realIndex = successImages.findIndex(item => item.url === file.url && item.path === file.path)
  293. const urls = successImages.map(item => item.url || item.path)
  294. uni.previewImage({ current: realIndex, urls, loop: true })
  295. return
  296. }
  297. uni.navigateTo({
  298. url: `/pages/common/webview?url=${encodeURIComponent(url)}&title=${encodeURIComponent(name)}`
  299. })
  300. }
  301. // ==============================================
  302. // 上传 / 删除 / 重试
  303. // ==============================================
  304. const deleteFile = (index) => {
  305. const item = innerFileList.value[index]
  306. innerFileList.value.splice(index, 1)
  307. emit('delete', item, index)
  308. }
  309. const handleChoose = () => {
  310. if (props.disabled || props.readonly) return
  311. const count = props.limit - innerFileList.value.length
  312. uni.chooseFile({
  313. type: props.fileMediatype,
  314. count,
  315. success: (res) => {
  316. const files = res.tempFiles || res.tempFilePaths.map((p, i) => ({
  317. path: p, name: `file_${i}`
  318. }))
  319. emit('select', { tempFiles: files })
  320. tempFileQueue.value = files
  321. if (props.autoUpload) startUpload()
  322. }
  323. })
  324. }
  325. const startUpload = async () => {
  326. const files = tempFileQueue.value
  327. tempFileQueue.value = []
  328. for (const file of files) await uploadFile(file)
  329. }
  330. const uploadFile = (fileItem) => {
  331. return new Promise((resolve) => {
  332. innerFileList.value.push({ ...fileItem, status: 'uploading', progress: 0 })
  333. const index = innerFileList.value.length - 1
  334. const url = props.action || config.Host80 + props.uploadUrl
  335. const task = uni.uploadFile({
  336. url,
  337. filePath: fileItem.path,
  338. name: props.uploadName,
  339. header: { 'Access-Token': userToken.value, ...props.uploadHeaders },
  340. formData: props.uploadData,
  341. success: (res) => {
  342. const result = props.responseHandler(res.data)
  343. if (result.success) {
  344. innerFileList.value[index].progress = 100
  345. innerFileList.value[index].status = 'success'
  346. innerFileList.value[index].url = config.Host80 + result.path
  347. innerFileList.value[index].path = result.path
  348. emit('success', innerFileList.value[index])
  349. } else {
  350. innerFileList.value[index].status = 'error'
  351. uni.showToast({ title: result.message, icon: 'error' })
  352. emit('fail', result.message)
  353. }
  354. resolve(result)
  355. },
  356. fail: () => {
  357. innerFileList.value[index].status = 'error'
  358. uni.showToast({ title: '上传失败', icon: 'error' })
  359. emit('fail', '网络异常')
  360. resolve(null)
  361. }
  362. })
  363. task.onProgressUpdate((p) => {
  364. innerFileList.value[index].progress = p.progress
  365. emit('progress', p, index)
  366. })
  367. })
  368. }
  369. const reUploadFile = (index) => {
  370. const file = innerFileList.value[index]
  371. uploadFile(file)
  372. }
  373. </script>
  374. <style scoped>
  375. /* 布局 */
  376. .uni-file-picker__container {
  377. display: flex;
  378. flex-wrap: wrap;
  379. margin: -5px;
  380. width: 100%;
  381. }
  382. .file-picker__box {
  383. position: relative;
  384. width: 33.3%;
  385. height: 0;
  386. padding-top: 33.3%;
  387. box-sizing: border-box;
  388. }
  389. .file-picker__box-content {
  390. position: absolute;
  391. top: 0;
  392. right: 0;
  393. bottom: 0;
  394. left: 0;
  395. margin: 5px;
  396. border-radius: 5px;
  397. overflow: hidden;
  398. background: #f7f7f7;
  399. }
  400. /* 图片 */
  401. .file-image {
  402. width: 100%;
  403. height: 100%;
  404. }
  405. /* 文件封面 */
  406. .file-cover {
  407. width: 100%;
  408. height: 100%;
  409. display: flex;
  410. align-items: center;
  411. justify-content: center;
  412. flex-direction: column;
  413. color: var(--bs-emphasis-color);
  414. }
  415. /* 视频 */
  416. .video-box {
  417. position: relative;
  418. }
  419. .video-play-icon {
  420. position: absolute;
  421. font-size: 30px;
  422. color: var(--bs-emphasis-color);
  423. background: rgba(0, 0, 0, 0.5);
  424. width: 50px;
  425. height: 50px;
  426. border-radius: 50%;
  427. display: flex;
  428. align-items: center;
  429. justify-content: center;
  430. }
  431. /* 文件类型颜色 */
  432. .file-pdf {
  433. background: #ff4f4f;
  434. }
  435. .file-word {
  436. background: #3a7ff5;
  437. }
  438. .file-excel {
  439. background: #24a148;
  440. }
  441. .file-video {
  442. background: #000;
  443. }
  444. .file-other {
  445. background: #f7f7f7;
  446. }
  447. .file-big-icon {
  448. font-size: 16px;
  449. font-weight: bold;
  450. margin-bottom: 4px;
  451. }
  452. .file-ext-name {
  453. font-size: 12px;
  454. opacity: 0.9;
  455. }
  456. /* 添加按钮 */
  457. .is-add {
  458. display: flex;
  459. align-items: center;
  460. justify-content: center;
  461. background: #f7f7f7;
  462. }
  463. .upload-icon {
  464. color: var(--bs-heading-color);
  465. }
  466. /* 删除按钮 */
  467. .icon-del-box {
  468. position: absolute;
  469. top: 3px;
  470. right: 3px;
  471. width: 26px;
  472. height: 26px;
  473. border-radius: 50%;
  474. background: rgba(0, 0, 0, 0.5);
  475. display: flex;
  476. align-items: center;
  477. justify-content: center;
  478. z-index: 10;
  479. transform: rotate(-45deg);
  480. }
  481. .icon-del {
  482. width: 15px;
  483. height: 2px;
  484. background: #fff;
  485. border-radius: 2px;
  486. }
  487. .rotate {
  488. position: absolute;
  489. transform: rotate(90deg);
  490. }
  491. /* 进度 */
  492. .file-picker__progress {
  493. position: absolute;
  494. bottom: 0;
  495. left: 0;
  496. right: 0;
  497. z-index: 2;
  498. }
  499. /* 失败遮罩 */
  500. .file-picker__mask {
  501. position: absolute;
  502. top: 0;
  503. left: 0;
  504. right: 0;
  505. bottom: 0;
  506. background: rgba(0, 0, 0, 0.4);
  507. color: var(--bs-emphasis-color);
  508. display: flex;
  509. align-items: center;
  510. justify-content: center;
  511. font-size: 12px;
  512. }
  513. /* 只读模式 */
  514. .file-list {
  515. padding: 5px;
  516. }
  517. .file-item {
  518. display: flex;
  519. align-items: center;
  520. gap: 10px;
  521. padding: 10px;
  522. background: #f8f8f8;
  523. border-radius: 8px;
  524. margin-bottom: 10px;
  525. }
  526. .file-thumb,
  527. .file-icon {
  528. width: 60px;
  529. height: 60px;
  530. border-radius: 6px;
  531. }
  532. .file-icon {
  533. background: #eee;
  534. display: flex;
  535. align-items: center;
  536. justify-content: center;
  537. }
  538. .file-icon-text {
  539. font-size: 12px;
  540. font-weight: bold;
  541. }
  542. .file-name {
  543. flex: 1;
  544. font-size: 14px;
  545. color: var(--bs-heading-color);
  546. }
  547. .empty-text {
  548. text-align: center;
  549. color: var(--bs-heading-color);
  550. padding: 20px 0;
  551. }
  552. </style>