km-file-upload.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. <template>
  2. <view class="form-item">
  3. <view class="form-file-upload">
  4. <!-- 上传 -->
  5. <view
  6. class="panel"
  7. v-for="(item, index) in list"
  8. :key="index"
  9. :style="{
  10. height: `${height}px`,
  11. width: `${height}px`
  12. }"
  13. >
  14. <!-- 移除按钮 -->
  15. <img
  16. @tap="removeFile(index)"
  17. class="close"
  18. src="../../static/delete.png"
  19. />
  20. <!-- 图片显示 -->
  21. <img
  22. v-if="item.is_img"
  23. class="img-show"
  24. :src="item.path"
  25. @tap="previewImage(item.path)"
  26. alt="文件加载失败"
  27. />
  28. <!-- 视频显示第一帧 -->
  29. <!-- #ifdef H5 -->
  30. <img
  31. v-else-if="item.is_video"
  32. class="img-show"
  33. :src="item.video_cover"
  34. @tap="previewFile(item.success_path)"
  35. alt="视频封面加载失败"
  36. />
  37. <!-- #endif -->
  38. <!-- #ifndef H5 -->
  39. <img
  40. v-else-if="item.is_video"
  41. class="img-show"
  42. :src="item.video_cover"
  43. :style="{
  44. 'border-radius': `${radius}px`
  45. }"
  46. @tap="previewFile(item.success_path)"
  47. alt="视频封面加载失败"
  48. />
  49. <!-- #endif -->
  50. <!-- 文件显示 -->
  51. <view v-else class="img-name" @tap="previewFile(item.success_path)">
  52. <img class="img" src="../../static/file.png" />
  53. <text class="text-two-line">{{ item.type }}</text>
  54. </view>
  55. <!-- 待上传,正在上传,上传失败 -->
  56. <view v-if="item.status != 2" class="upload-loading">
  57. <!-- 上传进度 -->
  58. <text v-if="item.status == 1">{{ progress }}%</text>
  59. <!-- 上传错误 -->
  60. <img v-if="item.status == 3" src="../../static/error.png" />
  61. </view>
  62. </view>
  63. <!-- 上传按钮 -->
  64. <view
  65. v-if="list.length < maxFile && !disabled"
  66. @tap.stop="chooseFile"
  67. class="slot-box"
  68. :style="{
  69. height: `${height}px`,
  70. width: `${height}px`
  71. }"
  72. >
  73. <slot>
  74. <view class="upload-btn">
  75. <img src="../../static/upload.png" />
  76. </view>
  77. </slot>
  78. </view>
  79. </view>
  80. <!-- 视频预览 -->
  81. <view
  82. v-if="is_preview_video"
  83. class="preview-video"
  84. @touchmove.stop.prevent="() => {}"
  85. >
  86. <text class="close" @tap="hidePreviewVideo">关闭</text>
  87. <video class="video" :src="preview_video_src"></video>
  88. </view>
  89. <!-- 临时视频组件 -->
  90. <video
  91. id="tmp-video"
  92. ref="tmp-video"
  93. v-show="false"
  94. :src="tmp_video_src"
  95. ></video>
  96. </view>
  97. </template>
  98. <script>
  99. export default {
  100. name: 'form-file-upload',
  101. props: {
  102. maxFile: {
  103. // 最大文件数
  104. type: Number,
  105. default: 1
  106. },
  107. disabled: {
  108. // 是否禁用
  109. type: Boolean,
  110. default: false
  111. },
  112. height: {
  113. // 宽度和高度
  114. type: Number,
  115. default: 50
  116. },
  117. action: {
  118. // 请求url
  119. type: String,
  120. default: ''
  121. },
  122. headers: {
  123. // 请求头
  124. type: Object,
  125. default: () => {}
  126. },
  127. name: {
  128. // 上传 的key
  129. type: String,
  130. default: 'file'
  131. },
  132. timeout: {
  133. // 超时时间 ms
  134. type: Number,
  135. default: 1 * 60 * 1000
  136. },
  137. formData: {
  138. // 表单其他参数
  139. type: Object,
  140. default: () => {}
  141. },
  142. // 事件
  143. onTimeout: {
  144. // 超时事件
  145. type: Function,
  146. default: () => function () {}
  147. },
  148. onProgress: {
  149. // 上传进度
  150. type: Function,
  151. default: () => function () {}
  152. },
  153. onError: {
  154. // 上传错误
  155. type: Function,
  156. default: () => function () {}
  157. }
  158. // 回调
  159. // @success
  160. // slot(插槽)
  161. // #default
  162. },
  163. data() {
  164. return {
  165. list: [
  166. // {
  167. // status: 0, // 0待上传 1正在上传 2上传成功 3上传失败
  168. // success_path: '', // 上传成功文件
  169. // is_img: false, // 是否是图片 true是 false否
  170. // is_video: false, // 是否是视频 true是 false否
  171. // path: '', // 待上传显示的文件
  172. // type: '', // 文件类型
  173. // video_cover: '', // 封面
  174. // ...item, // path: 待上传显示的文件 type:文件类型
  175. // }
  176. ], // 已上传列表
  177. upload_index: 0, // 当前上传的文件索引
  178. progress: 0, // 上传进度
  179. is_preview_video: false, // 是否预览视频
  180. preview_video_src: '', // 视频预览的路径
  181. h5_preview_file_src: '', // h5 文件预览路径
  182. tmp_video_src: '' // 临时视频组件路径
  183. }
  184. },
  185. methods: {
  186. // 选择图片上传
  187. chooseFile() {
  188. const _this = this
  189. let list_tmp = [] // 临时存放需要上传的文件列表
  190. if (!this.action) {
  191. let title = '请绑定上传路径'
  192. console.error(title)
  193. return
  194. }
  195. // #ifdef H5
  196. uni.chooseFile({
  197. count: this.maxFile,
  198. success(e) {
  199. // 提取文件列表
  200. for (let i = 0; i < e.tempFilePaths.length; i++) {
  201. list_tmp.push({
  202. status: 0, // 0待上传 1正在上传 2上传成功 3上传失败
  203. success_path: '', // 上传成功文件
  204. is_img: _this.jugdePictrue(e.tempFiles[i].type), // 是否是图片 true是 false否
  205. is_video: _this.jugdeVideo(e.tempFiles[i].type), // 是否是视频 true是 false否
  206. path: e.tempFilePaths[i],
  207. type: e.tempFiles[i].type,
  208. file: e.tempFiles[i]
  209. })
  210. }
  211. _this.execFile(list_tmp)
  212. }
  213. })
  214. // #endif
  215. // #ifdef MP-WEIXIN
  216. uni.showActionSheet({
  217. itemList: ['图片', '视频', '文件'],
  218. success(e) {
  219. let index = e.tapIndex
  220. switch (index) {
  221. case 0: // 图片
  222. _this.mpChooseImg()
  223. break
  224. case 1: // 视频
  225. _this.mpChooseVideo()
  226. break
  227. case 2: // 文件
  228. _this.mpChooseFile()
  229. break
  230. }
  231. }
  232. })
  233. // #endif
  234. },
  235. // 小程序选择图片
  236. mpChooseImg() {
  237. const _this = this
  238. let list_tmp = [] // 临时存放需要上传的文件列表
  239. uni.chooseImage({
  240. success(e) {
  241. // 提取文件列表
  242. e.tempFiles.forEach(item => {
  243. list_tmp.push({
  244. status: 0, // 0待上传 1正在上传 2上传成功 3上传失败
  245. success_path: '', // 上传成功文件
  246. is_img: true, // 是否是图片 true是 false否
  247. is_video: false, // 是否是视频 true是 false否
  248. path: item.path,
  249. type: 'image'
  250. // ...item, // path: 待上传显示的文件 type:文件类型
  251. })
  252. })
  253. _this.execFile(list_tmp)
  254. }
  255. })
  256. },
  257. // 小程序选择视频
  258. mpChooseVideo() {
  259. const _this = this
  260. let list_tmp = [] // 临时存放需要上传的文件列表
  261. uni.chooseVideo({
  262. success(e) {
  263. list_tmp.push({
  264. status: 0, // 0待上传 1正在上传 2上传成功 3上传失败
  265. success_path: '', // 上传成功文件
  266. is_img: false, // 是否是图片 true是 false否
  267. is_video: true, // 是否是视频 true是 false否
  268. path: e.tempFilePath,
  269. type: 'video',
  270. video_cover: e.thumbTempFilePath
  271. })
  272. _this.execFile(list_tmp)
  273. }
  274. })
  275. },
  276. // 小程序选择文件
  277. mpChooseFile() {
  278. const _this = this
  279. let list_tmp = [] // 临时存放需要上传的文件列表
  280. wx.chooseMessageFile({
  281. count: this.maxFile,
  282. success: async function (e) {
  283. // 提取文件列表
  284. e.tempFiles.forEach(item => {
  285. list_tmp.push({
  286. status: 0, // 0待上传 1正在上传 2上传成功 3上传失败
  287. success_path: '', // 上传成功文件
  288. is_img: _this.jugdePictrue(item.type), // 是否是图片 true是 false否
  289. is_video: _this.jugdeVideo(item.type), // 是否是视频 true是 false否
  290. ...item // path: 待上传显示的文件 type:文件类型
  291. })
  292. })
  293. _this.execFile(list_tmp)
  294. }
  295. })
  296. },
  297. // 处理选择的文件并上传
  298. async execFile(list_tmp) {
  299. // 判断已上传文件是否小于最大可传文件数,大则截取
  300. if (this.list.length + list_tmp.length > this.maxFile) {
  301. let max_len = this.list.length - list_tmp.length
  302. list_tmp = list_tmp.slice(0, max_len - 1)
  303. }
  304. // 上传文件
  305. this.list = [...this.list, ...list_tmp]
  306. let len = this.list.length
  307. for (let i = this.upload_index; i < len; i++) {
  308. this.list[this.upload_index].status = 1
  309. let r = await this.uploadFile(this.list[this.upload_index].file)
  310. if (!r) {
  311. // 上传失败
  312. this.list[this.upload_index].status = 3
  313. } else {
  314. // 上传成功
  315. let obj = JSON.parse(JSON.stringify(this.list[this.upload_index]))
  316. obj.status = 2
  317. obj.success_path = r
  318. // #ifdef H5
  319. if (obj.is_video) {
  320. obj.video_cover = await this.getVideoOneImgH5(obj.path)
  321. }
  322. // #endif
  323. this.list.splice(this.upload_index, 1, obj)
  324. }
  325. this.upload_index++
  326. this.progress = 0
  327. }
  328. let arr = this.list.map(item => item.success_path)
  329. this.$emit('success', arr)
  330. },
  331. // 上传文件到服务器
  332. async uploadFile(file) {
  333. const _this = this
  334. let res = this.xhr(file)
  335. return res
  336. },
  337. // xhr 封装
  338. xhr(file) {
  339. let _this = this
  340. return new Promise((resolv, reject) => {
  341. let form_data = new FormData()
  342. form_data.append(_this.name, file)
  343. // 载入其他表单参数
  344. if (_this.formData) {
  345. Object.keys(_this.formData).forEach(key => {
  346. form_data.append(key, _this.formData[key])
  347. })
  348. }
  349. let xhr = new XMLHttpRequest()
  350. xhr.timeout = err => {
  351. _this.timeout.call(null, err)
  352. reject(false)
  353. }
  354. xhr.ontimeout = _this.onTimeout
  355. xhr.onprogress = _this.onProgress
  356. xhr.onerror = err => {
  357. _this.onError.call(null, err)
  358. reject(false)
  359. }
  360. xhr.onload = () => {
  361. let response = JSON.parse(xhr.response)
  362. resolv(response.data.url)
  363. }
  364. xhr.open('POST', _this.action)
  365. // 载入请求头
  366. if (_this.headers) {
  367. Object.keys(_this.headers).forEach(key => {
  368. xhr.setRequestHeader(key, _this.headers[key])
  369. })
  370. }
  371. xhr.send(form_data)
  372. })
  373. },
  374. // 移除文件
  375. removeFile(index) {
  376. this.upload_index--
  377. this.list.splice(index, 1)
  378. },
  379. // 图片预览
  380. previewImage(path) {
  381. // 把列表中的图片全部取出来
  382. let list = this.list
  383. .map(item => {
  384. if (item.is_img) {
  385. return item.path
  386. }
  387. return ''
  388. })
  389. .filter(item => item)
  390. uni.previewImage({
  391. urls: list,
  392. current: path
  393. })
  394. },
  395. // 文件预览
  396. previewFile(path) {
  397. let tmp_arr = path.split('.')
  398. let file_type = tmp_arr[tmp_arr.length - 1] // 获取文件后缀
  399. // #ifdef MP-WEIXIN | MP-ALIPAY
  400. // 当前支持的文件预览
  401. let arr = ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx']
  402. let flag = arr.some(item => item == file_type) // 该文件是否支持预览
  403. if (flag) {
  404. uni.openDocument({
  405. filePath: path,
  406. fileType: file_type, // 支付宝小程序,文件类型必填
  407. fail() {
  408. uni.showToast({
  409. title: '文档打开失败',
  410. icon: 'none'
  411. })
  412. }
  413. })
  414. }
  415. // #endif
  416. // #ifdef H5
  417. let arr = ['doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx']
  418. let flag = arr.some(item => item == file_type) // 该文件是否支持预览
  419. if (flag) {
  420. this.previewFileH5(path)
  421. return
  422. } else if (file_type == 'pdf') {
  423. // pdf 文件预览
  424. this.previewPDFh5(path)
  425. return
  426. }
  427. // #endif
  428. // 如果文件是视频
  429. if (this.jugdeVideo(file_type)) {
  430. this.previewVideo(path)
  431. return
  432. }
  433. uni.showToast({
  434. title: '该文件不支持预览',
  435. icon: 'none'
  436. })
  437. },
  438. // 视频预览
  439. previewVideo(path) {
  440. this.is_preview_video = true
  441. this.preview_video_src = path
  442. },
  443. // 关闭视频预览
  444. hidePreviewVideo() {
  445. this.is_preview_video = false
  446. this.preview_video_src = ''
  447. },
  448. // h5 办公文件预览
  449. previewFileH5(path) {
  450. let url = encodeURIComponent(path)
  451. this.h5_preview_file_src =
  452. 'http://view.officeapps.live.com/op/view.aspx?src=' + url
  453. window.open(this.h5_preview_file_src)
  454. },
  455. // H5 截取视频第一帧
  456. getVideoOneImgH5(path) {
  457. const _this = this
  458. return new Promise((resove, reject) => {
  459. let video = document.createElement('video')
  460. video.src = path
  461. video.addEventListener('loadeddata', () => {
  462. video.play() // 防止空白截图
  463. setTimeout(() => {
  464. video.pause()
  465. let salc = 0.5
  466. let canvas = document.createElement('canvas')
  467. canvas.width = video.videoWidth * salc
  468. canvas.height = video.videoHeight * salc
  469. canvas
  470. .getContext('2d')
  471. .drawImage(video, 0, 0, canvas.width, canvas.height)
  472. let base64 = canvas.toDataURL('image/png')
  473. resove(base64)
  474. }, 500)
  475. })
  476. })
  477. },
  478. // h5 预览 pdf 文件
  479. previewPDFh5(path) {
  480. uni.showToast({
  481. title: '暂不支持浏览 pdf 文件',
  482. icon: 'none'
  483. })
  484. },
  485. // 判断是否是视频
  486. jugdeVideo(type) {
  487. let reg = ['video', 'VIDEO', 'mp4', 'avi', 'wmv', '3gp', 'flv']
  488. return reg.some(item => type.includes(item))
  489. },
  490. // 判断是否是图片
  491. jugdePictrue(type) {
  492. let reg = ['image', 'IMAGE', 'bmp', 'jpg', 'png', 'gif', 'jpeg']
  493. return reg.some(item => type.includes(item))
  494. }
  495. }
  496. }
  497. </script>
  498. <style lang="scss" scoped>
  499. .form-item {
  500. }
  501. .form-file-upload {
  502. display: flex;
  503. align-items: center;
  504. flex-wrap: wrap;
  505. .panel {
  506. flex-shrink: 0;
  507. position: relative;
  508. background-color: #f6f7f8;
  509. margin: 20rpx;
  510. border-radius: 10rpx;
  511. display: flex;
  512. justify-content: center;
  513. align-items: center;
  514. // &:nth-child(4n) {
  515. // margin-right: 0;
  516. // }
  517. .img-show {
  518. width: 100%;
  519. height: 100%;
  520. }
  521. .close {
  522. position: absolute;
  523. right: 0;
  524. top: 0;
  525. width: 26rpx;
  526. height: 26rpx;
  527. transform: translateX(30%) translateY(-30%);
  528. z-index: 9;
  529. padding: 10rpx;
  530. background-color: #fff;
  531. border-radius: 50%;
  532. }
  533. .img-name {
  534. width: 100%;
  535. display: flex;
  536. flex-direction: column;
  537. justify-content: center;
  538. align-items: center;
  539. font-size: 10px;
  540. color: #b3b5b9;
  541. overflow: hidden;
  542. .img {
  543. width: 50rpx;
  544. height: 50rpx;
  545. }
  546. text {
  547. width: 100%;
  548. text-align: center;
  549. span {
  550. display: inline-block;
  551. width: 100%;
  552. }
  553. }
  554. }
  555. .upload-loading {
  556. position: absolute;
  557. width: 100%;
  558. height: 100%;
  559. font-size: 32rpx;
  560. color: white;
  561. background-color: rgba($color: #000000, $alpha: 0.5);
  562. display: flex;
  563. align-items: center;
  564. justify-content: center;
  565. img {
  566. width: 50rpx;
  567. height: 50rpx;
  568. }
  569. }
  570. }
  571. .upload-btn {
  572. height: 100%;
  573. width: 100%;
  574. border-radius: 10rpx;
  575. display: flex;
  576. justify-content: center;
  577. align-items: center;
  578. border: 1px dashed #ccc;
  579. img {
  580. width: 50%;
  581. height: 50%;
  582. }
  583. }
  584. }
  585. .preview-video {
  586. position: fixed;
  587. top: 0;
  588. left: 0;
  589. width: 100vw;
  590. height: 100vh;
  591. z-index: 999;
  592. background-color: black;
  593. display: flex;
  594. align-items: center;
  595. justify-content: center;
  596. overflow: hidden;
  597. .video {
  598. width: 100%;
  599. max-width: 100%;
  600. max-height: 100%;
  601. z-index: -1;
  602. }
  603. .close {
  604. position: fixed;
  605. right: 40rpx;
  606. top: 40rpx;
  607. color: $uni-color-primary;
  608. font-size: 32rpx;
  609. }
  610. }
  611. .preview-file-h5 {
  612. position: fixed;
  613. top: 0;
  614. left: 0;
  615. width: 100vw;
  616. height: 100vh;
  617. z-index: 999;
  618. overflow: hidden;
  619. background-color: black;
  620. .close {
  621. position: fixed;
  622. right: 40rpx;
  623. top: 40rpx;
  624. color: $uni-color-primary;
  625. font-size: 32rpx;
  626. }
  627. }
  628. </style>