htz-image-upload.vue 16 KB

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