xfx-image-upload原版.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. <template>
  2. <view class="xfx-image-upload-list">
  3. <!-- 上传按钮 -->
  4. <view class="xfx-image-upload-Item xfx-image-upload-Item-add" v-if="uploadLists.length<max && add"
  5. @click="chooseFile">
  6. <uni-icons type='camera' style="font-size:60rpx"> </uni-icons>
  7. <!-- <u-icon name='camera-fill' size='45'></u-icon> -->
  8. <text class="text-upload">点击上传</text>
  9. </view>
  10. <view class="xfx-image-upload-Item" v-for="(item,index) in uploadLists" :key="item.url">
  11. <view class="xfx-image-upload-Item-video" v-if="(!/.(gif|jpg|jpeg|png|gif|jpg|png)$/i.test(item))">
  12. <image :disabled="false" :controls="false" :src="item+'?x-oss-process=video/snapshot,t_0,f_jpg'"
  13. mode="">
  14. <view class="xfx-image-upload-Item-video-fixed" @click="previewVideo(item)">
  15. <!-- <uni-icons type='videocam' style="font-size:60rpx"> </uni-icons> -->
  16. <u-icon size='80' name='play-right-fill' color="#ffffff"></u-icon>
  17. </view>
  18. <view class="xfx-image-upload-Item-del-cover" v-if="remove && previewVideoSrc==''"
  19. @click="imgDel(index)">×</view>
  20. </image>
  21. </view>
  22. <image v-else :src="item" @click="imgPreview(item)"></image>
  23. <view class="xfx-image-upload-Item-del" v-if="remove" @click="imgDel(index)">×</view>
  24. </view>
  25. <!-- flex布局 起占位作用 -->
  26. <view class="xfx-image-upload-Item" v-if="uploadLists.length<max-1">
  27. </view>
  28. <view class="preview-full" v-if="previewVideoSrc!=''">
  29. <video :autoplay="true" :src="previewVideoSrc" :show-fullscreen-btn="false">
  30. <cover-view class="preview-full-close" @click="previewVideoClose"> ×
  31. </cover-view>
  32. </video>
  33. </view>
  34. <!-- -->
  35. </view>
  36. </template>
  37. <style>
  38. </style>
  39. <script>
  40. //请求头token
  41. import {
  42. getToken
  43. } from '@/utils/auth'
  44. import UniIcons from '@/components/uni-icons/uni-icons.vue'
  45. export default {
  46. name: 'xfx-image-upload',
  47. props: {
  48. max: { //展示图片最大值
  49. type: Number,
  50. default: 6,
  51. },
  52. chooseNum: { //选择图片数
  53. type: Number,
  54. default: 6,
  55. },
  56. name: { //发到后台的文件参数名
  57. type: String,
  58. default: 'file',
  59. },
  60. remove: { //是否展示删除按钮
  61. type: Boolean,
  62. default: true,
  63. },
  64. add: { //是否展示添加按钮
  65. type: Boolean,
  66. default: true,
  67. },
  68. disabled: { //是否禁用
  69. type: Boolean,
  70. default: false,
  71. },
  72. sourceType: { //选择照片来源 【ps:H5就别费劲了,设置了也没用。不是我说的,官方文档就这样!!!】
  73. type: Array,
  74. default: () => ['album', 'camera'],
  75. },
  76. action: { //上传地址
  77. type: String,
  78. default: '',
  79. },
  80. headers: { //上传的请求头部
  81. type: Object,
  82. default: () => {
  83. return {
  84. Authorization: getToken()
  85. }
  86. },
  87. },
  88. formData: { //HTTP 请求中其他额外的 form data
  89. type: Object,
  90. default: () => {},
  91. },
  92. compress: { //是否需要压缩
  93. type: Boolean,
  94. default: true,
  95. },
  96. quality: { //压缩质量,范围0~100
  97. type: Number,
  98. default: 80,
  99. },
  100. value: { //受控图片列表
  101. type: Array,
  102. default: () => [],
  103. },
  104. uploadSuccess: {
  105. default: (res) => {
  106. return {
  107. success: false,
  108. url: ''
  109. }
  110. },
  111. },
  112. mediaType: { //文件类型 image/video/all
  113. type: String,
  114. default: 'image',
  115. },
  116. maxDuration: { //拍摄视频最长拍摄时间,单位秒。最长支持 60 秒。 (只针对拍摄视频有用)
  117. type: Number,
  118. default: 60,
  119. },
  120. camera: { //'front'、'back',默认'back'(只针对拍摄视频有用)
  121. type: String,
  122. default: 'back',
  123. },
  124. },
  125. components: {
  126. UniIcons
  127. },
  128. data() {
  129. return {
  130. uploadLists: [],
  131. mediaTypeData: ['image', 'video', 'all'],
  132. previewVideoSrc: '',
  133. // header:{
  134. // 'Authorization':''
  135. // }
  136. }
  137. },
  138. mounted: function() {
  139. console.log(this.action)
  140. this.headers.Authorization = getToken()
  141. console.log(this.headers)
  142. this.$nextTick(function() {
  143. this.uploadLists = this.value;
  144. if (this.mediaTypeData.indexOf(this.mediaType) == -1) {
  145. uni.showModal({
  146. title: '提示',
  147. content: 'mediaType参数不正确',
  148. showCancel: false,
  149. success: function(res) {
  150. if (res.confirm) {
  151. //console.log('用户点击确定');
  152. } else if (res.cancel) {
  153. //console.log('用户点击取消');
  154. }
  155. }
  156. });
  157. }
  158. });
  159. },
  160. watch: {
  161. value(val, oldVal) {
  162. console.log('value', val, oldVal)
  163. this.uploadLists = val;
  164. },
  165. },
  166. methods: {
  167. previewVideo(src) {
  168. this.previewVideoSrc = src;
  169. // this.previewVideoSrc =
  170. // 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-fbd63a76-dc76-485c-b711-f79f2986daeb/ba804d82-860b-4d1a-a706-5a4c8ce137c3.mp4'
  171. },
  172. previewVideoClose() {
  173. this.previewVideoSrc = ''
  174. console.log('previewVideoClose', this.previewVideoSrc)
  175. },
  176. imgDel(index) {
  177. uni.showModal({
  178. title: '提示',
  179. content: '您确定要删除么?',
  180. success: (res) => {
  181. if (res.confirm) {
  182. // this.uploadLists.splice(index, 1)
  183. // this.$emit("input", this.uploadLists);
  184. // this.$emit("imgDelete", this.uploadLists);
  185. let delUrl = this.uploadLists[index]
  186. this.uploadLists.splice(index, 1)
  187. this.$emit("input", this.uploadLists);
  188. this.$emit("imgDelete", {
  189. del: delUrl,
  190. tempFilePaths: this.uploadLists
  191. });
  192. } else if (res.cancel) {}
  193. }
  194. });
  195. },
  196. imgPreview(index) {
  197. var imgData = this.uploadLists.filter(item => /.(gif|jpg|jpeg|png|gif|jpg|png)$/i.test(item)) //只预览图片的
  198. uni.previewImage({
  199. urls: imgData,
  200. current: index,
  201. loop: true,
  202. });
  203. },
  204. chooseFile() {
  205. if (this.disabled) {
  206. return false;
  207. }
  208. switch (this.mediaTypeData.indexOf(this.mediaType)) {
  209. case 1: //视频
  210. this.videoAdd();
  211. break;
  212. case 2: //全部
  213. uni.showActionSheet({
  214. itemList: ['相册', '视频'],
  215. success: (res) => {
  216. if (res.tapIndex == 1) {
  217. this.videoAdd();
  218. } else if (res.tapIndex == 0) {
  219. this.imgAdd();
  220. }
  221. },
  222. fail: (res) => {
  223. console.log(res.errMsg);
  224. }
  225. });
  226. break;
  227. default: //图片
  228. this.imgAdd();
  229. break;
  230. }
  231. //if(this.mediaType=='image'){
  232. },
  233. videoAdd() {
  234. console.log('videoAdd')
  235. let nowNum = Math.abs(this.uploadLists.length - this.max);
  236. let thisNum = (this.chooseNum > nowNum ? nowNum : this.chooseNum) //可选数量
  237. uni.chooseVideo({
  238. compressed: this.compress,
  239. sourceType: this.sourceType,
  240. camera: this.camera,
  241. maxDuration: this.maxDuration,
  242. success: (res) => {
  243. console.log('videoAdd', res)
  244. console.log(res.tempFilePath)
  245. this.chooseSuccessMethod([res.tempFilePath], 1)
  246. //this.imgUpload([res.tempFilePath]);
  247. //console.log('tempFiles', res)
  248. // if (this.action == '') { //未配置上传路径
  249. // this.$emit("chooseSuccess", res.tempFilePaths);
  250. // } else {
  251. // if (this.compress && (res.tempFiles[0].size / 1024 > 1025)) { //设置了需要压缩 并且 文件大于1M,进行压缩上传
  252. // this.imgCompress(res.tempFilePaths);
  253. // } else {
  254. // this.imgUpload(res.tempFilePaths);
  255. // }
  256. // }
  257. }
  258. });
  259. },
  260. imgAdd() {
  261. console.log('imgAdd')
  262. let nowNum = Math.abs(this.uploadLists.length - this.max);
  263. let thisNum = (this.chooseNum > nowNum ? nowNum : this.chooseNum) //可选数量
  264. console.log('nowNum', nowNum)
  265. console.log('thisNum', thisNum)
  266. // #ifdef APP-PLUS
  267. if (this.sourceType.length > 1) {
  268. uni.showActionSheet({
  269. itemList: ['拍摄', '从手机相册选择'],
  270. success: (res) => {
  271. if (res.tapIndex == 1) {
  272. this.appGallery(thisNum);
  273. } else if (res.tapIndex == 0) {
  274. this.appCamera();
  275. }
  276. },
  277. fail: (res) => {
  278. console.log(res.errMsg);
  279. }
  280. });
  281. }
  282. if (this.sourceType.length == 1 && this.sourceType.indexOf('album') > -1) {
  283. this.appGallery(thisNum);
  284. }
  285. if (this.sourceType.length == 1 && this.sourceType.indexOf('camera') > -1) {
  286. this.appCamera();
  287. }
  288. // #endif
  289. //#ifndef APP-PLUS
  290. uni.chooseImage({
  291. count: thisNum,
  292. sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  293. sourceType: this.sourceType,
  294. success: (res) => {
  295. this.chooseSuccessMethod(res.tempFilePaths, 0)
  296. //console.log('tempFiles', res)
  297. // if (this.action == '') { //未配置上传路径
  298. // this.$emit("chooseSuccess", res.tempFilePaths);
  299. // } else {
  300. // if (this.compress && (res.tempFiles[0].size / 1024 > 1025)) { //设置了需要压缩 并且 文件大于1M,进行压缩上传
  301. // this.imgCompress(res.tempFilePaths);
  302. // } else {
  303. // this.imgUpload(res.tempFilePaths);
  304. // }
  305. // }
  306. }
  307. });
  308. // #endif
  309. },
  310. appCamera() {
  311. var cmr = plus.camera.getCamera();
  312. var res = cmr.supportedImageResolutions[0];
  313. var fmt = cmr.supportedImageFormats[0];
  314. //console.log("Resolution: " + res + ", Format: " + fmt);
  315. cmr.captureImage((path) => {
  316. //alert("Capture image success: " + path);
  317. this.chooseSuccessMethod([path], 0)
  318. },
  319. (error) => {
  320. //alert("Capture image failed: " + error.message);
  321. console.log("Capture image failed: " + error.message)
  322. }, {
  323. resolution: res,
  324. format: fmt
  325. }
  326. );
  327. },
  328. appGallery(maxNum) {
  329. plus.gallery.pick((res) => {
  330. this.chooseSuccessMethod(res.files, 0)
  331. }, function(e) {
  332. //console.log("取消选择图片");
  333. }, {
  334. filter: "image",
  335. multiple: true,
  336. maximum: maxNum
  337. });
  338. },
  339. chooseSuccessMethod(filePaths, type) {
  340. if (this.action == '') { //未配置上传路径
  341. // this.value.push({url:filePaths[0]})
  342. // console.log(this.value)
  343. // this.uploadLists.push({url:filePaths[0]})
  344. this.$emit("chooseSuccess", filePaths, type); //filePaths 路径 type 0 为图片 1为视频
  345. } else {
  346. if (type == 1) {
  347. this.imgUpload(filePaths);
  348. } else {
  349. if (this.compress) { //设置了需要压缩
  350. this.imgCompress(filePaths);
  351. } else {
  352. this.imgUpload(filePaths);
  353. }
  354. }
  355. }
  356. },
  357. imgCompress(tempFilePaths) {
  358. uni.showLoading({
  359. title: '压缩中...'
  360. });
  361. let compressImgs = [];
  362. let results = [];
  363. tempFilePaths.forEach((item, index) => {
  364. compressImgs.push(new Promise((resolve, reject) => {
  365. // #ifndef H5
  366. uni.compressImage({
  367. src: item,
  368. quality: this.quality,
  369. success: res => {
  370. //console.log('compressImage', res.tempFilePath)
  371. results.push(res.tempFilePath);
  372. resolve(res.tempFilePath);
  373. },
  374. fail: (err) => {
  375. //console.log(err.errMsg);
  376. reject(err);
  377. },
  378. complete: () => {
  379. //uni.hideLoading();
  380. }
  381. })
  382. // #endif
  383. // #ifdef H5
  384. this.canvasDataURL(item, {
  385. quality: this.quality / 100
  386. }, (base64Codes) => {
  387. //this.imgUpload(base64Codes);
  388. results.push(base64Codes);
  389. resolve(base64Codes);
  390. })
  391. // #endif
  392. }))
  393. })
  394. Promise.all(compressImgs) //执行所有需请求的接口
  395. .then((results) => {
  396. uni.hideLoading();
  397. console.log('imgUpload', results)
  398. this.imgUpload(results);
  399. })
  400. .catch((res, object) => {
  401. uni.hideLoading();
  402. });
  403. },
  404. imgUpload(tempFilePaths) {
  405. // if (this.action == '') {
  406. // uni.showToast({
  407. // title: '未配置上传地址',
  408. // icon: 'none',
  409. // duration: 2000
  410. // });
  411. // return false;
  412. // }
  413. uni.showLoading({
  414. title: '上传中'
  415. });
  416. console.log('imgUpload', tempFilePaths)
  417. let uploadImgs = [];
  418. tempFilePaths.forEach((item, index) => {
  419. uploadImgs.push(new Promise((resolve, reject) => {
  420. // console.log(index, item)
  421. const uploadTask = uni.uploadFile({
  422. url: this.action, //仅为示例,非真实的接口地址
  423. filePath: item,
  424. name: this.name,
  425. fileType: 'image',
  426. formData: this.formData,
  427. header: this.headers,
  428. success: (uploadFileRes) => {
  429. //uni.hideLoading();
  430. //console.log(typeof this.uploadSuccess)
  431. //console.log('')
  432. if (typeof this.uploadSuccess == 'function') {
  433. if (this.uploadSuccess(uploadFileRes).success) {
  434. this.value.push(this.uploadSuccess(uploadFileRes)
  435. .url)
  436. this.$emit("input", this.uploadLists);
  437. }
  438. }
  439. resolve(uploadFileRes);
  440. this.$emit("uploadSuccess", uploadFileRes);
  441. },
  442. fail: (err) => {
  443. console.log(err);
  444. //uni.hideLoading();
  445. reject(err);
  446. this.$emit("uploadFail", err);
  447. },
  448. complete: () => {
  449. //uni.hideLoading();
  450. }
  451. });
  452. }))
  453. })
  454. Promise.all(uploadImgs) //执行所有需请求的接口
  455. .then((results) => {
  456. uni.hideLoading();
  457. })
  458. .catch((res, object) => {
  459. uni.hideLoading();
  460. this.$emit("uploadFail", res);
  461. });
  462. // uploadTask.onProgressUpdate((res) => {
  463. // //console.log('',)
  464. // uni.showLoading({
  465. // title: '上传中' + res.progress + '%'
  466. // });
  467. // if (res.progress == 100) {
  468. // uni.hideLoading();
  469. // }
  470. // });
  471. },
  472. canvasDataURL(path, obj, callback) {
  473. var img = new Image();
  474. img.src = path;
  475. img.onload = function() {
  476. var that = this;
  477. // 默认按比例压缩
  478. var w = that.width,
  479. h = that.height,
  480. scale = w / h;
  481. w = obj.width || w;
  482. h = obj.height || (w / scale);
  483. var quality = 0.8; // 默认图片质量为0.8
  484. //生成canvas
  485. var canvas = document.createElement('canvas');
  486. var ctx = canvas.getContext('2d');
  487. // 创建属性节点
  488. var anw = document.createAttribute("width");
  489. anw.nodeValue = w;
  490. var anh = document.createAttribute("height");
  491. anh.nodeValue = h;
  492. canvas.setAttributeNode(anw);
  493. canvas.setAttributeNode(anh);
  494. ctx.drawImage(that, 0, 0, w, h);
  495. // 图像质量
  496. if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
  497. quality = obj.quality;
  498. }
  499. // quality值越小,所绘制出的图像越模糊
  500. var base64 = canvas.toDataURL('image/jpeg', quality);
  501. // 回调函数返回base64的值
  502. callback(base64);
  503. }
  504. },
  505. }
  506. }
  507. </script>
  508. <style>
  509. .preview-full {
  510. position: fixed;
  511. top: 0;
  512. left: 0;
  513. bottom: 0;
  514. width: 100%;
  515. height: 100%;
  516. z-index: 1002;
  517. }
  518. .preview-full video {
  519. width: 100%;
  520. height: 100%;
  521. z-index: 1002;
  522. }
  523. .preview-full-close {
  524. position: fixed;
  525. right: 32rpx;
  526. top: 25rpx;
  527. width: 80rpx;
  528. height: 80rpx;
  529. line-height: 60rpx;
  530. text-align: center;
  531. z-index: 1003;
  532. /* background-color: #808080; */
  533. color: #fff;
  534. font-size: 65rpx;
  535. font-weight: bold;
  536. text-shadow: 1px 2px 5px rgb(0 0 0);
  537. }
  538. /* .preview-full-close-before,
  539. .preview-full-close-after {
  540. position: absolute;
  541. top: 50%;
  542. left: 50%;
  543. content: '';
  544. height: 60rpx;
  545. margin-top: -30rpx;
  546. width: 6rpx;
  547. margin-left: -3rpx;
  548. background-color: #FFFFFF;
  549. z-index: 20000;
  550. }
  551. .preview-full-close-before {
  552. transform: rotate(45deg);
  553. }
  554. .preview-full-close-after {
  555. transform: rotate(-45deg);
  556. } */
  557. .xfx-image-upload-list {
  558. display: flex;
  559. flex-wrap: wrap;
  560. justify-content: space-between;
  561. }
  562. .xfx-image-upload-Item {
  563. width: 190rpx;
  564. height: 190rpx;
  565. margin-right: 25rpx;
  566. /* margin: 13rpx; */
  567. border-radius: 12rpx;
  568. position: relative;
  569. margin-bottom: 30rpx;
  570. }
  571. .xfx-image-upload-Item:nth-child(3n) {
  572. margin-right: 0;
  573. }
  574. .xfx-image-upload-Item image {
  575. width: 100%;
  576. height: 100%;
  577. border-radius: 12rpx;
  578. }
  579. .xfx-image-upload-Item-video {
  580. width: 100%;
  581. height: 100%;
  582. border-radius: 12rpx;
  583. position: relative;
  584. }
  585. .xfx-image-upload-Item-video-fixed {
  586. position: absolute;
  587. top: 0;
  588. left: 0;
  589. bottom: 0;
  590. width: 100%;
  591. height: 100%;
  592. border-radius: 12rpx;
  593. display: flex;
  594. justify-content: center;
  595. align-items: center;
  596. z-index: 50;
  597. }
  598. .xfx-image-upload-Item video {
  599. width: 100%;
  600. height: 100%;
  601. border-radius: 10rpx;
  602. }
  603. .xfx-image-upload-Item-add {
  604. /* font-size: 105rpx; */
  605. /* line-height: 160rpx; */
  606. padding-top: 56rpx;
  607. box-sizing: border-box;
  608. text-align: center;
  609. background-color: #F6F7F8;
  610. display: flex;
  611. flex-direction: column;
  612. align-items: center;
  613. }
  614. .text-upload {
  615. font-size: 24rpx;
  616. line-height: 33rpx;
  617. color: #A4A8AC;
  618. display: block;
  619. margin-top: 16rpx;
  620. }
  621. .xfx-image-upload-Item-del {
  622. border-radius: 50%;
  623. background-color: #F13629;
  624. font-size: 24rpx;
  625. position: absolute;
  626. width: 36rpx;
  627. height: 36rpx;
  628. line-height: 35rpx;
  629. text-align: center;
  630. top: -18rpx;
  631. right: -18rpx;
  632. z-index: 51;
  633. color: #fff;
  634. }
  635. .xfx-image-upload-Item-del-cover {
  636. border-radius: 50%;
  637. background-color: #F13629;
  638. font-size: 24rpx;
  639. position: absolute;
  640. width: 36rpx;
  641. height: 36rpx;
  642. text-align: center;
  643. top: -18rpx;
  644. right: -18rpx;
  645. color: #fff;
  646. /* #ifdef APP-PLUS */
  647. line-height: 25rpx;
  648. /* #endif */
  649. /* #ifndef APP-PLUS */
  650. line-height: 35rpx;
  651. /* #endif */
  652. z-index: 51;
  653. }
  654. </style>