uni-file-picker.vue 17 KB

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