You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

660 lines
16 KiB

3 weeks ago
  1. <template>
  2. <view class="uni-file-picker">
  3. <view v-if="title" class="uni-file-picker__header">
  4. <text class="file-title">{{ title }}</text>
  5. <text class="file-count">{{ filesList.length }}/{{ limitLength }}</text>
  6. </view>
  7. <upload-image v-if="fileMediatype === 'image' && showType === 'grid'" :readonly="readonly"
  8. :image-styles="imageStyles" :files-list="filesList" :limit="limitLength" :disablePreview="disablePreview"
  9. :delIcon="delIcon" @uploadFiles="uploadFiles" @choose="choose" @delFile="delFile">
  10. <slot>
  11. <view class="icon-add"></view>
  12. <view class="icon-add rotate"></view>
  13. </slot>
  14. </upload-image>
  15. <upload-file v-if="fileMediatype !== 'image' || showType !== 'grid'" :readonly="readonly"
  16. :list-styles="listStyles" :files-list="filesList" :showType="showType" :delIcon="delIcon"
  17. @uploadFiles="uploadFiles" @choose="choose" @delFile="delFile">
  18. <slot><button type="primary" size="mini">选择文件</button></slot>
  19. </upload-file>
  20. </view>
  21. </template>
  22. <script>
  23. import {
  24. chooseAndUploadFile,
  25. uploadCloudFiles
  26. } from './choose-and-upload-file.js'
  27. import {
  28. get_file_ext,
  29. get_extname,
  30. get_files_and_is_max,
  31. get_file_info,
  32. get_file_data
  33. } from './utils.js'
  34. import uploadImage from './upload-image.vue'
  35. import uploadFile from './upload-file.vue'
  36. let fileInput = null
  37. /**
  38. * FilePicker 文件选择上传
  39. * @description 文件选择上传组件可以选择图片视频等任意文件并上传到当前绑定的服务空间
  40. * @tutorial https://ext.dcloud.net.cn/plugin?id=4079
  41. * @property {Object|Array} value 组件数据通常用来回显 ,类型由return-type属性决定
  42. * @property {Boolean} disabled = [true|false] 组件禁用
  43. * @value true 禁用
  44. * @value false 取消禁用
  45. * @property {Boolean} readonly = [true|false] 组件只读不可选择不显示进度不显示删除按钮
  46. * @value true 只读
  47. * @value false 取消只读
  48. * @property {String} return-type = [array|object] 限制 value 格式当为 object 组件只能单选且会覆盖
  49. * @value array 规定 value 属性的类型为数组
  50. * @value object 规定 value 属性的类型为对象
  51. * @property {Boolean} disable-preview = [true|false] 禁用图片预览 mode:grid 时生效
  52. * @value true 禁用图片预览
  53. * @value false 取消禁用图片预览
  54. * @property {Boolean} del-icon = [true|false] 是否显示删除按钮
  55. * @value true 显示删除按钮
  56. * @value false 不显示删除按钮
  57. * @property {Boolean} auto-upload = [true|false] 是否自动上传值为true则只触发@select,可自行上传
  58. * @value true 自动上传
  59. * @value false 取消自动上传
  60. * @property {Number|String} limit 最大选择个数 h5 会自动忽略多选的部分
  61. * @property {String} title 组件标题右侧显示上传计数
  62. * @property {String} mode = [list|grid] 选择文件后的文件列表样式
  63. * @value list 列表显示
  64. * @value grid 宫格显示
  65. * @property {String} file-mediatype = [image|video|all] 选择文件类型
  66. * @value image 只选择图片
  67. * @value video 只选择视频
  68. * @value all 选择所有文件
  69. * @property {Array} file-extname 选择文件后缀根据 file-mediatype 属性而不同
  70. * @property {Object} list-style mode:list 时的样式
  71. * @property {Object} image-styles 选择文件后缀根据 file-mediatype 属性而不同
  72. * @event {Function} select 选择文件后触发
  73. * @event {Function} progress 文件上传时触发
  74. * @event {Function} success 上传成功触发
  75. * @event {Function} fail 上传失败触发
  76. * @event {Function} delete 文件从列表移除时触发
  77. */
  78. export default {
  79. name: 'uniFilePicker',
  80. components: {
  81. uploadImage,
  82. uploadFile
  83. },
  84. options: {
  85. virtualHost: true
  86. },
  87. emits: ['select', 'success', 'fail', 'progress', 'delete', 'update:modelValue', 'input'],
  88. props: {
  89. modelValue: {
  90. type: [Array, Object],
  91. default () {
  92. return []
  93. }
  94. },
  95. value: {
  96. type: [Array, Object],
  97. default () {
  98. return []
  99. }
  100. },
  101. disabled: {
  102. type: Boolean,
  103. default: false
  104. },
  105. disablePreview: {
  106. type: Boolean,
  107. default: false
  108. },
  109. delIcon: {
  110. type: Boolean,
  111. default: true
  112. },
  113. // 自动上传
  114. autoUpload: {
  115. type: Boolean,
  116. default: true
  117. },
  118. // 最大选择个数 ,h5只能限制单选或是多选
  119. limit: {
  120. type: [Number, String],
  121. default: 9
  122. },
  123. // 列表样式 grid | list | list-card
  124. mode: {
  125. type: String,
  126. default: 'grid'
  127. },
  128. // 选择文件类型 image/video/all
  129. fileMediatype: {
  130. type: String,
  131. default: 'image'
  132. },
  133. // 文件类型筛选
  134. fileExtname: {
  135. type: [Array, String],
  136. default () {
  137. return []
  138. }
  139. },
  140. title: {
  141. type: String,
  142. default: ''
  143. },
  144. listStyles: {
  145. type: Object,
  146. default () {
  147. return {
  148. // 是否显示边框
  149. border: true,
  150. // 是否显示分隔线
  151. dividline: true,
  152. // 线条样式
  153. borderStyle: {}
  154. }
  155. }
  156. },
  157. imageStyles: {
  158. type: Object,
  159. default () {
  160. return {
  161. width: 'auto',
  162. height: 'auto'
  163. }
  164. }
  165. },
  166. readonly: {
  167. type: Boolean,
  168. default: false
  169. },
  170. returnType: {
  171. type: String,
  172. default: 'array'
  173. },
  174. sizeType: {
  175. type: Array,
  176. default () {
  177. return ['original', 'compressed']
  178. }
  179. },
  180. sourceType: {
  181. type: Array,
  182. default () {
  183. return ['album', 'camera']
  184. }
  185. },
  186. provider: {
  187. type: String,
  188. default: '' // 默认上传到 unicloud 内置存储 extStorage 扩展存储
  189. }
  190. },
  191. data() {
  192. return {
  193. files: [],
  194. localValue: []
  195. }
  196. },
  197. watch: {
  198. value: {
  199. handler(newVal, oldVal) {
  200. this.setValue(newVal, oldVal)
  201. },
  202. immediate: true
  203. },
  204. modelValue: {
  205. handler(newVal, oldVal) {
  206. this.setValue(newVal, oldVal)
  207. },
  208. immediate: true
  209. },
  210. },
  211. computed: {
  212. filesList() {
  213. let files = []
  214. this.files.forEach(v => {
  215. files.push(v)
  216. })
  217. return files
  218. },
  219. showType() {
  220. if (this.fileMediatype === 'image') {
  221. return this.mode
  222. }
  223. return 'list'
  224. },
  225. limitLength() {
  226. if (this.returnType === 'object') {
  227. return 1
  228. }
  229. if (!this.limit) {
  230. return 1
  231. }
  232. if (this.limit >= 9) {
  233. return 9
  234. }
  235. return this.limit
  236. }
  237. },
  238. created() {
  239. // TODO 兼容不开通服务空间的情况
  240. if (!(uniCloud.config && uniCloud.config.provider)) {
  241. this.noSpace = true
  242. uniCloud.chooseAndUploadFile = chooseAndUploadFile
  243. }
  244. this.form = this.getForm('uniForms')
  245. this.formItem = this.getForm('uniFormsItem')
  246. if (this.form && this.formItem) {
  247. if (this.formItem.name) {
  248. this.rename = this.formItem.name
  249. this.form.inputChildrens.push(this)
  250. }
  251. }
  252. },
  253. methods: {
  254. /**
  255. * 公开用户使用清空文件
  256. * @param {Object} index
  257. */
  258. clearFiles(index) {
  259. if (index !== 0 && !index) {
  260. this.files = []
  261. this.$nextTick(() => {
  262. this.setEmit()
  263. })
  264. } else {
  265. this.files.splice(index, 1)
  266. }
  267. this.$nextTick(() => {
  268. this.setEmit()
  269. })
  270. },
  271. /**
  272. * 公开用户使用继续上传
  273. */
  274. upload() {
  275. let files = []
  276. this.files.forEach((v, index) => {
  277. if (v.status === 'ready' || v.status === 'error') {
  278. files.push(Object.assign({}, v))
  279. }
  280. })
  281. return this.uploadFiles(files)
  282. },
  283. async setValue(newVal, oldVal) {
  284. const newData = async (v) => {
  285. const reg = /cloud:\/\/([\w.]+\/?)\S*/
  286. let url = ''
  287. if(v.fileID){
  288. url = v.fileID
  289. }else{
  290. url = v.url
  291. }
  292. if (reg.test(url)) {
  293. v.fileID = url
  294. v.url = await this.getTempFileURL(url)
  295. }
  296. if(v.url) v.path = v.url
  297. return v
  298. }
  299. if (this.returnType === 'object') {
  300. if (newVal) {
  301. await newData(newVal)
  302. } else {
  303. newVal = {}
  304. }
  305. } else {
  306. if (!newVal) newVal = []
  307. for(let i =0 ;i < newVal.length ;i++){
  308. let v = newVal[i]
  309. await newData(v)
  310. }
  311. }
  312. this.localValue = newVal
  313. if (this.form && this.formItem &&!this.is_reset) {
  314. this.is_reset = false
  315. this.formItem.setValue(this.localValue)
  316. }
  317. let filesData = Object.keys(newVal).length > 0 ? newVal : [];
  318. this.files = [].concat(filesData)
  319. },
  320. /**
  321. * 选择文件
  322. */
  323. choose() {
  324. if (this.disabled) return
  325. if (this.files.length >= Number(this.limitLength) && this.showType !== 'grid' && this.returnType ===
  326. 'array') {
  327. uni.showToast({
  328. title: `您最多选择 ${this.limitLength} 个文件`,
  329. icon: 'none'
  330. })
  331. return
  332. }
  333. this.chooseFiles()
  334. },
  335. /**
  336. * 选择文件并上传
  337. */
  338. chooseFiles() {
  339. const _extname = get_extname(this.fileExtname)
  340. // 获取后缀
  341. uniCloud
  342. .chooseAndUploadFile({
  343. type: this.fileMediatype,
  344. compressed: false,
  345. sizeType: this.sizeType,
  346. sourceType: this.sourceType,
  347. // TODO 如果为空,video 有问题
  348. extension: _extname.length > 0 ? _extname : undefined,
  349. count: this.limitLength - this.files.length, //默认9
  350. onChooseFile: this.chooseFileCallback,
  351. onUploadProgress: progressEvent => {
  352. this.setProgress(progressEvent, progressEvent.index)
  353. }
  354. })
  355. .then(result => {
  356. this.setSuccessAndError(result.tempFiles)
  357. })
  358. .catch(err => {
  359. console.log('选择失败', err)
  360. })
  361. },
  362. /**
  363. * 选择文件回调
  364. * @param {Object} res
  365. */
  366. async chooseFileCallback(res) {
  367. const _extname = get_extname(this.fileExtname)
  368. const is_one = (Number(this.limitLength) === 1 &&
  369. this.disablePreview &&
  370. !this.disabled) ||
  371. this.returnType === 'object'
  372. // 如果这有一个文件 ,需要清空本地缓存数据
  373. if (is_one) {
  374. this.files = []
  375. }
  376. let {
  377. filePaths,
  378. files
  379. } = get_files_and_is_max(res, _extname)
  380. if (!(_extname && _extname.length > 0)) {
  381. filePaths = res.tempFilePaths
  382. files = res.tempFiles
  383. }
  384. let currentData = []
  385. for (let i = 0; i < files.length; i++) {
  386. if (this.limitLength - this.files.length <= 0) break
  387. files[i].uuid = Date.now()
  388. let filedata = await get_file_data(files[i], this.fileMediatype)
  389. filedata.progress = 0
  390. filedata.status = 'ready'
  391. // fix by mehaotian ,统一返回,删除也包含file对象
  392. let fileTempData = {
  393. ...filedata,
  394. file: files[i]
  395. }
  396. this.files.push(fileTempData)
  397. currentData.push(fileTempData)
  398. }
  399. this.$emit('select', {
  400. tempFiles: currentData,
  401. tempFilePaths: filePaths
  402. })
  403. res.tempFiles = files
  404. // 停止自动上传
  405. if (!this.autoUpload || this.noSpace) {
  406. res.tempFiles = []
  407. }
  408. res.tempFiles.forEach((fileItem, index) => {
  409. this.provider && (fileItem.provider = this.provider);
  410. const fileNameSplit = fileItem.name.split('.')
  411. const ext = fileNameSplit.pop()
  412. const fileName = fileNameSplit.join('.').replace(/[\s\/\?<>\\:\*\|":]/g, '_')
  413. fileItem.cloudPath = fileName + '_' + Date.now() + '_' + index + '.' + ext
  414. })
  415. },
  416. /**
  417. * 批传
  418. * @param {Object} e
  419. */
  420. uploadFiles(files) {
  421. files = [].concat(files)
  422. return uploadCloudFiles.call(this, files, 5, res => {
  423. this.setProgress(res, res.index, true)
  424. })
  425. .then(result => {
  426. this.setSuccessAndError(result)
  427. return result;
  428. })
  429. .catch(err => {
  430. console.log(err)
  431. })
  432. },
  433. /**
  434. * 成功或失败
  435. */
  436. async setSuccessAndError(res, fn) {
  437. let successData = []
  438. let errorData = []
  439. let tempFilePath = []
  440. let errorTempFilePath = []
  441. for (let i = 0; i < res.length; i++) {
  442. const item = res[i]
  443. const index = item.uuid ? this.files.findIndex(p => p.uuid === item.uuid) : item.index
  444. if (index === -1 || !this.files) break
  445. if (item.errMsg === 'request:fail') {
  446. this.files[index].url = item.path
  447. this.files[index].status = 'error'
  448. this.files[index].errMsg = item.errMsg
  449. // this.files[index].progress = -1
  450. errorData.push(this.files[index])
  451. errorTempFilePath.push(this.files[index].url)
  452. } else {
  453. this.files[index].errMsg = ''
  454. this.files[index].fileID = item.url
  455. const reg = /cloud:\/\/([\w.]+\/?)\S*/
  456. if (reg.test(item.url)) {
  457. this.files[index].url = await this.getTempFileURL(item.url)
  458. }else{
  459. this.files[index].url = item.url
  460. }
  461. this.files[index].status = 'success'
  462. this.files[index].progress += 1
  463. successData.push(this.files[index])
  464. tempFilePath.push(this.files[index].fileID)
  465. }
  466. }
  467. if (successData.length > 0) {
  468. this.setEmit()
  469. // 状态改变返回
  470. this.$emit('success', {
  471. tempFiles: this.backObject(successData),
  472. tempFilePaths: tempFilePath
  473. })
  474. }
  475. if (errorData.length > 0) {
  476. this.$emit('fail', {
  477. tempFiles: this.backObject(errorData),
  478. tempFilePaths: errorTempFilePath
  479. })
  480. }
  481. },
  482. /**
  483. * 获取进度
  484. * @param {Object} progressEvent
  485. * @param {Object} index
  486. * @param {Object} type
  487. */
  488. setProgress(progressEvent, index, type) {
  489. const fileLenth = this.files.length
  490. const percentNum = (index / fileLenth) * 100
  491. const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
  492. let idx = index
  493. if (!type) {
  494. idx = this.files.findIndex(p => p.uuid === progressEvent.tempFile.uuid)
  495. }
  496. if (idx === -1 || !this.files[idx]) return
  497. // fix by mehaotian 100 就会消失,-1 是为了让进度条消失
  498. this.files[idx].progress = percentCompleted - 1
  499. // 上传中
  500. this.$emit('progress', {
  501. index: idx,
  502. progress: parseInt(percentCompleted),
  503. tempFile: this.files[idx]
  504. })
  505. },
  506. /**
  507. * 删除文件
  508. * @param {Object} index
  509. */
  510. delFile(index) {
  511. this.$emit('delete', {
  512. index,
  513. tempFile: this.files[index],
  514. tempFilePath: this.files[index].url
  515. })
  516. this.files.splice(index, 1)
  517. this.$nextTick(() => {
  518. this.setEmit()
  519. })
  520. },
  521. /**
  522. * 获取文件名和后缀
  523. * @param {Object} name
  524. */
  525. getFileExt(name) {
  526. const last_len = name.lastIndexOf('.')
  527. const len = name.length
  528. return {
  529. name: name.substring(0, last_len),
  530. ext: name.substring(last_len + 1, len)
  531. }
  532. },
  533. /**
  534. * 处理返回事件
  535. */
  536. setEmit() {
  537. let data = []
  538. if (this.returnType === 'object') {
  539. data = this.backObject(this.files)[0]
  540. this.localValue = data?data:null
  541. } else {
  542. data = this.backObject(this.files)
  543. if (!this.localValue) {
  544. this.localValue = []
  545. }
  546. this.localValue = [...data]
  547. }
  548. // #ifdef VUE3
  549. this.$emit('update:modelValue', this.localValue)
  550. // #endif
  551. // #ifndef VUE3
  552. this.$emit('input', this.localValue)
  553. // #endif
  554. },
  555. /**
  556. * 处理返回参数
  557. * @param {Object} files
  558. */
  559. backObject(files) {
  560. let newFilesData = []
  561. files.forEach(v => {
  562. newFilesData.push({
  563. extname: v.extname,
  564. fileType: v.fileType,
  565. image: v.image,
  566. name: v.name,
  567. path: v.path,
  568. size: v.size,
  569. fileID:v.fileID,
  570. url: v.url,
  571. // 修改删除一个文件后不能再上传的bug, #694
  572. uuid: v.uuid,
  573. status: v.status,
  574. cloudPath: v.cloudPath
  575. })
  576. })
  577. return newFilesData
  578. },
  579. async getTempFileURL(fileList) {
  580. fileList = {
  581. fileList: [].concat(fileList)
  582. }
  583. const urls = await uniCloud.getTempFileURL(fileList)
  584. return urls.fileList[0].tempFileURL || ''
  585. },
  586. /**
  587. * 获取父元素实例
  588. */
  589. getForm(name = 'uniForms') {
  590. let parent = this.$parent;
  591. let parentName = parent.$options.name;
  592. while (parentName !== name) {
  593. parent = parent.$parent;
  594. if (!parent) return false;
  595. parentName = parent.$options.name;
  596. }
  597. return parent;
  598. }
  599. }
  600. }
  601. </script>
  602. <style>
  603. .uni-file-picker {
  604. /* #ifndef APP-NVUE */
  605. box-sizing: border-box;
  606. overflow: hidden;
  607. width: 100%;
  608. /* #endif */
  609. flex: 1;
  610. }
  611. .uni-file-picker__header {
  612. padding-top: 5px;
  613. padding-bottom: 10px;
  614. /* #ifndef APP-NVUE */
  615. display: flex;
  616. /* #endif */
  617. justify-content: space-between;
  618. }
  619. .file-title {
  620. font-size: 14px;
  621. color: #333;
  622. }
  623. .file-count {
  624. font-size: 14px;
  625. color: #999;
  626. }
  627. .icon-add {
  628. width: 50px;
  629. height: 5px;
  630. background-color: #f1f1f1;
  631. border-radius: 2px;
  632. }
  633. .rotate {
  634. position: absolute;
  635. transform: rotate(90deg);
  636. }
  637. </style>