uni-file-picker.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  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. options: {
  87. virtualHost: true
  88. },
  89. emits: ['select', 'success', 'fail', 'progress', 'delete', 'update:modelValue', 'input'],
  90. props: {
  91. // #ifdef VUE3
  92. modelValue: {
  93. type: [Array, Object],
  94. default () {
  95. return []
  96. }
  97. },
  98. // #endif
  99. // #ifndef VUE3
  100. value: {
  101. type: [Array, Object],
  102. default () {
  103. return []
  104. }
  105. },
  106. // #endif
  107. disabled: {
  108. type: Boolean,
  109. default: false
  110. },
  111. disablePreview: {
  112. type: Boolean,
  113. default: false
  114. },
  115. delIcon: {
  116. type: Boolean,
  117. default: true
  118. },
  119. // 自动上传
  120. autoUpload: {
  121. type: Boolean,
  122. default: true
  123. },
  124. // 最大选择个数 ,h5只能限制单选或是多选
  125. limit: {
  126. type: [Number, String],
  127. default: 9
  128. },
  129. // 列表样式 grid | list | list-card
  130. mode: {
  131. type: String,
  132. default: 'grid'
  133. },
  134. // 选择文件类型 image/video/all
  135. fileMediatype: {
  136. type: String,
  137. default: 'image'
  138. },
  139. // 文件类型筛选
  140. fileExtname: {
  141. type: [Array, String],
  142. default () {
  143. return []
  144. }
  145. },
  146. title: {
  147. type: String,
  148. default: ''
  149. },
  150. listStyles: {
  151. type: Object,
  152. default () {
  153. return {
  154. // 是否显示边框
  155. border: true,
  156. // 是否显示分隔线
  157. dividline: true,
  158. // 线条样式
  159. borderStyle: {}
  160. }
  161. }
  162. },
  163. imageStyles: {
  164. type: Object,
  165. default () {
  166. return {
  167. width: 'auto',
  168. height: 'auto'
  169. }
  170. }
  171. },
  172. readonly: {
  173. type: Boolean,
  174. default: false
  175. },
  176. returnType: {
  177. type: String,
  178. default: 'array'
  179. },
  180. sizeType: {
  181. type: Array,
  182. default () {
  183. return ['original', 'compressed']
  184. }
  185. }
  186. },
  187. data() {
  188. return {
  189. files: [],
  190. localValue: []
  191. }
  192. },
  193. watch: {
  194. // #ifndef VUE3
  195. value: {
  196. handler(newVal, oldVal) {
  197. this.setValue(newVal, oldVal)
  198. },
  199. immediate: true
  200. },
  201. // #endif
  202. // #ifdef VUE3
  203. modelValue: {
  204. handler(newVal, oldVal) {
  205. this.setValue(newVal, oldVal)
  206. },
  207. immediate: true
  208. },
  209. // #endif
  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. // TODO 如果为空,video 有问题
  347. extension: _extname.length > 0 ? _extname : undefined,
  348. count: this.limitLength - this.files.length, //默认9
  349. onChooseFile: this.chooseFileCallback,
  350. onUploadProgress: progressEvent => {
  351. this.setProgress(progressEvent, progressEvent.index)
  352. }
  353. })
  354. .then(result => {
  355. this.setSuccessAndError(result.tempFiles)
  356. })
  357. .catch(err => {
  358. console.log('选择失败', err)
  359. })
  360. },
  361. /**
  362. * 选择文件回调
  363. * @param {Object} res
  364. */
  365. async chooseFileCallback(res) {
  366. const _extname = get_extname(this.fileExtname)
  367. const is_one = (Number(this.limitLength) === 1 &&
  368. this.disablePreview &&
  369. !this.disabled) ||
  370. this.returnType === 'object'
  371. // 如果这有一个文件 ,需要清空本地缓存数据
  372. if (is_one) {
  373. this.files = []
  374. }
  375. let {
  376. filePaths,
  377. files
  378. } = get_files_and_is_max(res, _extname)
  379. if (!(_extname && _extname.length > 0)) {
  380. filePaths = res.tempFilePaths
  381. files = res.tempFiles
  382. }
  383. let currentData = []
  384. for (let i = 0; i < files.length; i++) {
  385. if (this.limitLength - this.files.length <= 0) break
  386. files[i].uuid = Date.now()
  387. let filedata = await get_file_data(files[i], this.fileMediatype)
  388. filedata.progress = 0
  389. filedata.status = 'ready'
  390. this.files.push(filedata)
  391. currentData.push({
  392. ...filedata,
  393. file: files[i]
  394. })
  395. }
  396. this.$emit('select', {
  397. tempFiles: currentData,
  398. tempFilePaths: filePaths
  399. })
  400. res.tempFiles = files
  401. // 停止自动上传
  402. if (!this.autoUpload || this.noSpace) {
  403. res.tempFiles = []
  404. }
  405. },
  406. /**
  407. * 批传
  408. * @param {Object} e
  409. */
  410. uploadFiles(files) {
  411. files = [].concat(files)
  412. return uploadCloudFiles.call(this, files, 5, res => {
  413. this.setProgress(res, res.index, true)
  414. })
  415. .then(result => {
  416. this.setSuccessAndError(result)
  417. return result;
  418. })
  419. .catch(err => {
  420. console.log(err)
  421. })
  422. },
  423. /**
  424. * 成功或失败
  425. */
  426. async setSuccessAndError(res, fn) {
  427. let successData = []
  428. let errorData = []
  429. let tempFilePath = []
  430. let errorTempFilePath = []
  431. for (let i = 0; i < res.length; i++) {
  432. const item = res[i]
  433. const index = item.uuid ? this.files.findIndex(p => p.uuid === item.uuid) : item.index
  434. if (index === -1 || !this.files) break
  435. if (item.errMsg === 'request:fail') {
  436. this.files[index].url = item.path
  437. this.files[index].status = 'error'
  438. this.files[index].errMsg = item.errMsg
  439. // this.files[index].progress = -1
  440. errorData.push(this.files[index])
  441. errorTempFilePath.push(this.files[index].url)
  442. } else {
  443. this.files[index].errMsg = ''
  444. this.files[index].fileID = item.url
  445. const reg = /cloud:\/\/([\w.]+\/?)\S*/
  446. if (reg.test(item.url)) {
  447. this.files[index].url = await this.getTempFileURL(item.url)
  448. }else{
  449. this.files[index].url = item.url
  450. }
  451. this.files[index].status = 'success'
  452. this.files[index].progress += 1
  453. successData.push(this.files[index])
  454. tempFilePath.push(this.files[index].fileID)
  455. }
  456. }
  457. if (successData.length > 0) {
  458. this.setEmit()
  459. // 状态改变返回
  460. this.$emit('success', {
  461. tempFiles: this.backObject(successData),
  462. tempFilePaths: tempFilePath
  463. })
  464. }
  465. if (errorData.length > 0) {
  466. this.$emit('fail', {
  467. tempFiles: this.backObject(errorData),
  468. tempFilePaths: errorTempFilePath
  469. })
  470. }
  471. },
  472. /**
  473. * 获取进度
  474. * @param {Object} progressEvent
  475. * @param {Object} index
  476. * @param {Object} type
  477. */
  478. setProgress(progressEvent, index, type) {
  479. const fileLenth = this.files.length
  480. const percentNum = (index / fileLenth) * 100
  481. const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
  482. let idx = index
  483. if (!type) {
  484. idx = this.files.findIndex(p => p.uuid === progressEvent.tempFile.uuid)
  485. }
  486. if (idx === -1 || !this.files[idx]) return
  487. // fix by mehaotian 100 就会消失,-1 是为了让进度条消失
  488. this.files[idx].progress = percentCompleted - 1
  489. // 上传中
  490. this.$emit('progress', {
  491. index: idx,
  492. progress: parseInt(percentCompleted),
  493. tempFile: this.files[idx]
  494. })
  495. },
  496. /**
  497. * 删除文件
  498. * @param {Object} index
  499. */
  500. delFile(index) {
  501. this.$emit('delete', {
  502. tempFile: this.files[index],
  503. tempFilePath: this.files[index].url
  504. })
  505. this.files.splice(index, 1)
  506. this.$nextTick(() => {
  507. this.setEmit()
  508. })
  509. },
  510. /**
  511. * 获取文件名和后缀
  512. * @param {Object} name
  513. */
  514. getFileExt(name) {
  515. const last_len = name.lastIndexOf('.')
  516. const len = name.length
  517. return {
  518. name: name.substring(0, last_len),
  519. ext: name.substring(last_len + 1, len)
  520. }
  521. },
  522. /**
  523. * 处理返回事件
  524. */
  525. setEmit() {
  526. let data = []
  527. if (this.returnType === 'object') {
  528. data = this.backObject(this.files)[0]
  529. this.localValue = data?data:null
  530. } else {
  531. data = this.backObject(this.files)
  532. if (!this.localValue) {
  533. this.localValue = []
  534. }
  535. this.localValue = [...data]
  536. }
  537. // #ifdef VUE3
  538. this.$emit('update:modelValue', this.localValue)
  539. // #endif
  540. // #ifndef VUE3
  541. this.$emit('input', this.localValue)
  542. // #endif
  543. },
  544. /**
  545. * 处理返回参数
  546. * @param {Object} files
  547. */
  548. backObject(files) {
  549. let newFilesData = []
  550. files.forEach(v => {
  551. newFilesData.push({
  552. extname: v.extname,
  553. fileType: v.fileType,
  554. image: v.image,
  555. name: v.name,
  556. path: v.path,
  557. size: v.size,
  558. fileID:v.fileID,
  559. url: v.url
  560. })
  561. })
  562. return newFilesData
  563. },
  564. async getTempFileURL(fileList) {
  565. fileList = {
  566. fileList: [].concat(fileList)
  567. }
  568. const urls = await uniCloud.getTempFileURL(fileList)
  569. return urls.fileList[0].tempFileURL || ''
  570. },
  571. /**
  572. * 获取父元素实例
  573. */
  574. getForm(name = 'uniForms') {
  575. let parent = this.$parent;
  576. let parentName = parent.$options.name;
  577. while (parentName !== name) {
  578. parent = parent.$parent;
  579. if (!parent) return false;
  580. parentName = parent.$options.name;
  581. }
  582. return parent;
  583. }
  584. }
  585. }
  586. </script>
  587. <style>
  588. .uni-file-picker {
  589. /* #ifndef APP-NVUE */
  590. box-sizing: border-box;
  591. overflow: hidden;
  592. width: 100%;
  593. /* #endif */
  594. flex: 1;
  595. }
  596. .uni-file-picker__header {
  597. padding-top: 5px;
  598. padding-bottom: 10px;
  599. /* #ifndef APP-NVUE */
  600. display: flex;
  601. /* #endif */
  602. justify-content: space-between;
  603. }
  604. .file-title {
  605. font-size: 14px;
  606. color: #333;
  607. }
  608. .file-count {
  609. font-size: 14px;
  610. color: #999;
  611. }
  612. .is-add {
  613. /* #ifndef APP-NVUE */
  614. display: flex;
  615. /* #endif */
  616. align-items: center;
  617. justify-content: center;
  618. }
  619. .icon-add {
  620. width: 50px;
  621. height: 5px;
  622. background-color: #f1f1f1;
  623. border-radius: 2px;
  624. }
  625. .rotate {
  626. position: absolute;
  627. transform: rotate(90deg);
  628. }
  629. </style>