uni-file-picker.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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. modelValue: {
  92. type: [Array, Object],
  93. default () {
  94. return []
  95. }
  96. },
  97. value: {
  98. type: [Array, Object],
  99. default () {
  100. return []
  101. }
  102. },
  103. disabled: {
  104. type: Boolean,
  105. default: false
  106. },
  107. disablePreview: {
  108. type: Boolean,
  109. default: false
  110. },
  111. delIcon: {
  112. type: Boolean,
  113. default: true
  114. },
  115. // 自动上传
  116. autoUpload: {
  117. type: Boolean,
  118. default: true
  119. },
  120. // 最大选择个数 ,h5只能限制单选或是多选
  121. limit: {
  122. type: [Number, String],
  123. default: 9
  124. },
  125. // 列表样式 grid | list | list-card
  126. mode: {
  127. type: String,
  128. default: 'grid'
  129. },
  130. // 选择文件类型 image/video/all
  131. fileMediatype: {
  132. type: String,
  133. default: 'image'
  134. },
  135. // 文件类型筛选
  136. fileExtname: {
  137. type: [Array, String],
  138. default () {
  139. return []
  140. }
  141. },
  142. title: {
  143. type: String,
  144. default: ''
  145. },
  146. listStyles: {
  147. type: Object,
  148. default () {
  149. return {
  150. // 是否显示边框
  151. border: true,
  152. // 是否显示分隔线
  153. dividline: true,
  154. // 线条样式
  155. borderStyle: {}
  156. }
  157. }
  158. },
  159. imageStyles: {
  160. type: Object,
  161. default () {
  162. return {
  163. width: 'auto',
  164. height: 'auto'
  165. }
  166. }
  167. },
  168. readonly: {
  169. type: Boolean,
  170. default: false
  171. },
  172. returnType: {
  173. type: String,
  174. default: 'array'
  175. },
  176. sizeType: {
  177. type: Array,
  178. default () {
  179. return ['original', 'compressed']
  180. }
  181. },
  182. sourceType: {
  183. type: Array,
  184. default () {
  185. return ['album', 'camera']
  186. }
  187. },
  188. provider: {
  189. type: String,
  190. default: '' // 默认上传到 unicloud 内置存储 extStorage 扩展存储
  191. }
  192. },
  193. data() {
  194. return {
  195. files: [],
  196. localValue: []
  197. }
  198. },
  199. watch: {
  200. value: {
  201. handler(newVal, oldVal) {
  202. this.setValue(newVal, oldVal)
  203. },
  204. immediate: true
  205. },
  206. modelValue: {
  207. handler(newVal, oldVal) {
  208. this.setValue(newVal, oldVal)
  209. },
  210. immediate: true
  211. },
  212. },
  213. computed: {
  214. filesList() {
  215. let files = []
  216. this.files.forEach(v => {
  217. files.push(v)
  218. })
  219. return files
  220. },
  221. showType() {
  222. if (this.fileMediatype === 'image') {
  223. return this.mode
  224. }
  225. return 'list'
  226. },
  227. limitLength() {
  228. if (this.returnType === 'object') {
  229. return 1
  230. }
  231. if (!this.limit) {
  232. return 1
  233. }
  234. if (this.limit >= 9) {
  235. return 9
  236. }
  237. return this.limit
  238. }
  239. },
  240. created() {
  241. // TODO 兼容不开通服务空间的情况
  242. if (!(uniCloud.config && uniCloud.config.provider)) {
  243. this.noSpace = true
  244. uniCloud.chooseAndUploadFile = chooseAndUploadFile
  245. }
  246. this.form = this.getForm('uniForms')
  247. this.formItem = this.getForm('uniFormsItem')
  248. if (this.form && this.formItem) {
  249. if (this.formItem.name) {
  250. this.rename = this.formItem.name
  251. this.form.inputChildrens.push(this)
  252. }
  253. }
  254. },
  255. methods: {
  256. /**
  257. * 公开用户使用,清空文件
  258. * @param {Object} index
  259. */
  260. clearFiles(index) {
  261. if (index !== 0 && !index) {
  262. this.files = []
  263. this.$nextTick(() => {
  264. this.setEmit()
  265. })
  266. } else {
  267. this.files.splice(index, 1)
  268. }
  269. this.$nextTick(() => {
  270. this.setEmit()
  271. })
  272. },
  273. /**
  274. * 公开用户使用,继续上传
  275. */
  276. upload() {
  277. let files = []
  278. this.files.forEach((v, index) => {
  279. if (v.status === 'ready' || v.status === 'error') {
  280. files.push(Object.assign({}, v))
  281. }
  282. })
  283. return this.uploadFiles(files)
  284. },
  285. async setValue(newVal, oldVal) {
  286. const newData = async (v) => {
  287. const reg = /cloud:\/\/([\w.]+\/?)\S*/
  288. let url = ''
  289. if(v.fileID){
  290. url = v.fileID
  291. }else{
  292. url = v.url
  293. }
  294. if (reg.test(url)) {
  295. v.fileID = url
  296. v.url = await this.getTempFileURL(url)
  297. }
  298. if(v.url) v.path = v.url
  299. return v
  300. }
  301. if (this.returnType === 'object') {
  302. if (newVal) {
  303. await newData(newVal)
  304. } else {
  305. newVal = {}
  306. }
  307. } else {
  308. if (!newVal) newVal = []
  309. for(let i =0 ;i < newVal.length ;i++){
  310. let v = newVal[i]
  311. await newData(v)
  312. }
  313. }
  314. this.localValue = newVal
  315. if (this.form && this.formItem &&!this.is_reset) {
  316. this.is_reset = false
  317. this.formItem.setValue(this.localValue)
  318. }
  319. let filesData = Object.keys(newVal).length > 0 ? newVal : [];
  320. this.files = [].concat(filesData)
  321. },
  322. /**
  323. * 选择文件
  324. */
  325. choose() {
  326. if (this.disabled) return
  327. if (this.files.length >= Number(this.limitLength) && this.showType !== 'grid' && this.returnType ===
  328. 'array') {
  329. uni.showToast({
  330. title: `您最多选择 ${this.limitLength} 个文件`,
  331. icon: 'none'
  332. })
  333. return
  334. }
  335. this.chooseFiles()
  336. },
  337. /**
  338. * 选择文件并上传
  339. */
  340. chooseFiles() {
  341. const _extname = get_extname(this.fileExtname)
  342. // 获取后缀
  343. uniCloud
  344. .chooseAndUploadFile({
  345. type: this.fileMediatype,
  346. compressed: false,
  347. sizeType: this.sizeType,
  348. sourceType: this.sourceType,
  349. // TODO 如果为空,video 有问题
  350. extension: _extname.length > 0 ? _extname : undefined,
  351. count: this.limitLength - this.files.length, //默认9
  352. onChooseFile: this.chooseFileCallback,
  353. onUploadProgress: progressEvent => {
  354. this.setProgress(progressEvent, progressEvent.index)
  355. }
  356. })
  357. .then(result => {
  358. this.setSuccessAndError(result.tempFiles)
  359. })
  360. .catch(err => {
  361. console.log('选择失败', err)
  362. })
  363. },
  364. /**
  365. * 选择文件回调
  366. * @param {Object} res
  367. */
  368. async chooseFileCallback(res) {
  369. const _extname = get_extname(this.fileExtname)
  370. const is_one = (Number(this.limitLength) === 1 &&
  371. this.disablePreview &&
  372. !this.disabled) ||
  373. this.returnType === 'object'
  374. // 如果这有一个文件 ,需要清空本地缓存数据
  375. if (is_one) {
  376. this.files = []
  377. }
  378. let {
  379. filePaths,
  380. files
  381. } = get_files_and_is_max(res, _extname)
  382. if (!(_extname && _extname.length > 0)) {
  383. filePaths = res.tempFilePaths
  384. files = res.tempFiles
  385. }
  386. let currentData = []
  387. for (let i = 0; i < files.length; i++) {
  388. if (this.limitLength - this.files.length <= 0) break
  389. files[i].uuid = Date.now()
  390. let filedata = await get_file_data(files[i], this.fileMediatype)
  391. filedata.progress = 0
  392. filedata.status = 'ready'
  393. this.files.push(filedata)
  394. currentData.push({
  395. ...filedata,
  396. file: files[i]
  397. })
  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. .is-add {
  628. /* #ifndef APP-NVUE */
  629. display: flex;
  630. /* #endif */
  631. align-items: center;
  632. justify-content: center;
  633. }
  634. .icon-add {
  635. width: 50px;
  636. height: 5px;
  637. background-color: #f1f1f1;
  638. border-radius: 2px;
  639. }
  640. .rotate {
  641. position: absolute;
  642. transform: rotate(90deg);
  643. }
  644. </style>