uni-file-picker.vue 16 KB

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