uni-file-picker.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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. return 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. if(v.url) 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. return uploadCloudFiles.call(this, files, 5, res => {
  410. this.setProgress(res, res.index, true)
  411. })
  412. .then(result => {
  413. this.setSuccessAndError(result)
  414. return result;
  415. })
  416. .catch(err => {
  417. console.log(err)
  418. })
  419. },
  420. /**
  421. * 成功或失败
  422. */
  423. async setSuccessAndError(res, fn) {
  424. let successData = []
  425. let errorData = []
  426. let tempFilePath = []
  427. let errorTempFilePath = []
  428. for (let i = 0; i < res.length; i++) {
  429. const item = res[i]
  430. const index = item.uuid ? this.files.findIndex(p => p.uuid === item.uuid) : item.index
  431. if (index === -1 || !this.files) break
  432. if (item.errMsg === 'request:fail') {
  433. this.files[index].url = item.path
  434. this.files[index].status = 'error'
  435. this.files[index].errMsg = item.errMsg
  436. // this.files[index].progress = -1
  437. errorData.push(this.files[index])
  438. errorTempFilePath.push(this.files[index].url)
  439. } else {
  440. this.files[index].errMsg = ''
  441. this.files[index].fileID = item.url
  442. const reg = /cloud:\/\/([\w.]+\/?)\S*/
  443. if (reg.test(item.url)) {
  444. this.files[index].url = await this.getTempFileURL(item.url)
  445. }else{
  446. this.files[index].url = item.url
  447. }
  448. this.files[index].status = 'success'
  449. this.files[index].progress += 1
  450. successData.push(this.files[index])
  451. tempFilePath.push(this.files[index].fileID)
  452. }
  453. }
  454. if (successData.length > 0) {
  455. this.setEmit()
  456. // 状态改变返回
  457. this.$emit('success', {
  458. tempFiles: this.backObject(successData),
  459. tempFilePaths: tempFilePath
  460. })
  461. }
  462. if (errorData.length > 0) {
  463. this.$emit('fail', {
  464. tempFiles: this.backObject(errorData),
  465. tempFilePaths: errorTempFilePath
  466. })
  467. }
  468. },
  469. /**
  470. * 获取进度
  471. * @param {Object} progressEvent
  472. * @param {Object} index
  473. * @param {Object} type
  474. */
  475. setProgress(progressEvent, index, type) {
  476. const fileLenth = this.files.length
  477. const percentNum = (index / fileLenth) * 100
  478. const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
  479. let idx = index
  480. if (!type) {
  481. idx = this.files.findIndex(p => p.uuid === progressEvent.tempFile.uuid)
  482. }
  483. if (idx === -1 || !this.files[idx]) return
  484. // fix by mehaotian 100 就会消失,-1 是为了让进度条消失
  485. this.files[idx].progress = percentCompleted - 1
  486. // 上传中
  487. this.$emit('progress', {
  488. index: idx,
  489. progress: parseInt(percentCompleted),
  490. tempFile: this.files[idx]
  491. })
  492. },
  493. /**
  494. * 删除文件
  495. * @param {Object} index
  496. */
  497. delFile(index) {
  498. this.$emit('delete', {
  499. tempFile: this.files[index],
  500. tempFilePath: this.files[index].url
  501. })
  502. this.files.splice(index, 1)
  503. this.$nextTick(() => {
  504. this.setEmit()
  505. })
  506. },
  507. /**
  508. * 获取文件名和后缀
  509. * @param {Object} name
  510. */
  511. getFileExt(name) {
  512. const last_len = name.lastIndexOf('.')
  513. const len = name.length
  514. return {
  515. name: name.substring(0, last_len),
  516. ext: name.substring(last_len + 1, len)
  517. }
  518. },
  519. /**
  520. * 处理返回事件
  521. */
  522. setEmit() {
  523. let data = []
  524. if (this.returnType === 'object') {
  525. data = this.backObject(this.files)[0]
  526. this.localValue = data?data:null
  527. } else {
  528. data = this.backObject(this.files)
  529. if (!this.localValue) {
  530. this.localValue = []
  531. }
  532. this.localValue = [...data]
  533. }
  534. // #ifdef VUE3
  535. this.$emit('update:modelValue', this.localValue)
  536. // #endif
  537. // #ifndef VUE3
  538. this.$emit('input', this.localValue)
  539. // #endif
  540. },
  541. /**
  542. * 处理返回参数
  543. * @param {Object} files
  544. */
  545. backObject(files) {
  546. let newFilesData = []
  547. files.forEach(v => {
  548. newFilesData.push({
  549. extname: v.extname,
  550. fileType: v.fileType,
  551. image: v.image,
  552. name: v.name,
  553. path: v.path,
  554. size: v.size,
  555. fileID:v.fileID,
  556. url: v.url
  557. })
  558. })
  559. return newFilesData
  560. },
  561. async getTempFileURL(fileList) {
  562. fileList = {
  563. fileList: [].concat(fileList)
  564. }
  565. const urls = await uniCloud.getTempFileURL(fileList)
  566. return urls.fileList[0].tempFileURL || ''
  567. },
  568. /**
  569. * 获取父元素实例
  570. */
  571. getForm(name = 'uniForms') {
  572. let parent = this.$parent;
  573. let parentName = parent.$options.name;
  574. while (parentName !== name) {
  575. parent = parent.$parent;
  576. if (!parent) return false;
  577. parentName = parent.$options.name;
  578. }
  579. return parent;
  580. }
  581. }
  582. }
  583. </script>
  584. <style>
  585. .uni-file-picker {
  586. /* #ifndef APP-NVUE */
  587. box-sizing: border-box;
  588. overflow: hidden;
  589. /* #endif */
  590. }
  591. .uni-file-picker__header {
  592. padding-top: 5px;
  593. padding-bottom: 10px;
  594. /* #ifndef APP-NVUE */
  595. display: flex;
  596. /* #endif */
  597. justify-content: space-between;
  598. }
  599. .file-title {
  600. font-size: 14px;
  601. color: #333;
  602. }
  603. .file-count {
  604. font-size: 14px;
  605. color: #999;
  606. }
  607. .is-add {
  608. /* #ifndef APP-NVUE */
  609. display: flex;
  610. /* #endif */
  611. align-items: center;
  612. justify-content: center;
  613. }
  614. .icon-add {
  615. width: 50px;
  616. height: 5px;
  617. background-color: #f1f1f1;
  618. border-radius: 2px;
  619. }
  620. .rotate {
  621. position: absolute;
  622. transform: rotate(90deg);
  623. }
  624. </style>