htz-image-upload.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. console.log("删除后:",this.uploadLists)
  173. this.$emit("input", this.uploadLists);
  174. this.$emit("imgDelete", {
  175. del: delUrl,
  176. tempFilePaths: this.uploadLists
  177. });
  178. } else if (res.cancel) {}
  179. }
  180. });
  181. },
  182. imgPreview(index) {
  183. var imgData = this.uploadLists.filter(item => /.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(item)) //只预览图片的
  184. uni.previewImage({
  185. urls: imgData,
  186. current: index,
  187. loop: true,
  188. });
  189. },
  190. chooseFile() {
  191. if (this.disabled) {
  192. return false;
  193. }
  194. switch (this.mediaTypeData.indexOf(this.mediaType)) {
  195. case 1: //视频
  196. this.videoAdd();
  197. break;
  198. case 2: //全部
  199. uni.showActionSheet({
  200. itemList: ['相册', '视频'],
  201. success: (res) => {
  202. if (res.tapIndex == 1) {
  203. this.videoAdd();
  204. } else if (res.tapIndex == 0) {
  205. this.imgAdd();
  206. }
  207. },
  208. fail: (res) => {
  209. console.log("err: ", res.errMsg);
  210. }
  211. });
  212. break;
  213. default: //图片
  214. this.imgAdd();
  215. break;
  216. }
  217. //if(this.mediaType=='image'){
  218. },
  219. videoAdd() {
  220. console.log('videoAdd')
  221. let nowNum = Math.abs(this.uploadLists.length - this.max);
  222. let thisNum = (this.chooseNum > nowNum ? nowNum : this.chooseNum) //可选数量
  223. uni.chooseVideo({
  224. compressed: this.compress,
  225. sourceType: this.sourceType,
  226. camera: this.camera,
  227. maxDuration: this.maxDuration,
  228. success: (res) => {
  229. console.log('videoAdd', res)
  230. console.log(res.tempFilePath)
  231. this.chooseSuccessMethod([res.tempFilePath], 1)
  232. //this.imgUpload([res.tempFilePath]);
  233. //console.log('tempFiles', res)
  234. // if (this.action == '') { //未配置上传路径
  235. // this.$emit("chooseSuccess", res.tempFilePaths);
  236. // } else {
  237. // if (this.compress && (res.tempFiles[0].size / 1024 > 1025)) { //设置了需要压缩 并且 文件大于1M,进行压缩上传
  238. // this.imgCompress(res.tempFilePaths);
  239. // } else {
  240. // this.imgUpload(res.tempFilePaths);
  241. // }
  242. // }
  243. }
  244. });
  245. },
  246. imgAdd() {
  247. console.log('imgAdd')
  248. let nowNum = Math.abs(this.uploadLists.length - this.max);
  249. let thisNum = (this.chooseNum > nowNum ? nowNum : this.chooseNum) //可选数量
  250. console.log('nowNum', nowNum)
  251. console.log('thisNum', thisNum)
  252. // #ifdef APP-PLUS
  253. if (this.sourceType.length > 1) {
  254. uni.showActionSheet({
  255. itemList: ['拍摄', '从手机相册选择'],
  256. success: (res) => {
  257. if (res.tapIndex == 1) {
  258. this.appGallery(thisNum);
  259. } else if (res.tapIndex == 0) {
  260. this.appCamera();
  261. }
  262. },
  263. fail: (res) => {
  264. console.log("err: ", res.errMsg);
  265. }
  266. });
  267. }
  268. if (this.sourceType.length == 1 && this.sourceType.indexOf('album') > -1) {
  269. this.appGallery(thisNum);
  270. }
  271. if (this.sourceType.length == 1 && this.sourceType.indexOf('camera') > -1) {
  272. this.appCamera();
  273. }
  274. // #endif
  275. //#ifndef APP-PLUS
  276. uni.chooseImage({
  277. count: thisNum,
  278. sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  279. sourceType: this.sourceType,
  280. success: (res) => {
  281. this.chooseSuccessMethod(res.tempFilePaths, 0)
  282. //console.log('tempFiles', res)
  283. // if (this.action == '') { //未配置上传路径
  284. // this.$emit("chooseSuccess", res.tempFilePaths);
  285. // } else {
  286. // if (this.compress && (res.tempFiles[0].size / 1024 > 1025)) { //设置了需要压缩 并且 文件大于1M,进行压缩上传
  287. // this.imgCompress(res.tempFilePaths);
  288. // } else {
  289. // this.imgUpload(res.tempFilePaths);
  290. // }
  291. // }
  292. }
  293. });
  294. // #endif
  295. },
  296. appCamera() {
  297. var cmr = plus.camera.getCamera();
  298. var res = cmr.supportedImageResolutions[0];
  299. var fmt = cmr.supportedImageFormats[0];
  300. //console.log("Resolution: " + res + ", Format: " + fmt);
  301. cmr.captureImage((path) => {
  302. //alert("Capture image success: " + path);
  303. this.chooseSuccessMethod([path], 0)
  304. },
  305. (error) => {
  306. //alert("Capture image failed: " + error.message);
  307. console.log("Capture image failed: " + error.message)
  308. }, {
  309. resolution: res,
  310. format: fmt
  311. }
  312. );
  313. },
  314. appGallery(maxNum) {
  315. plus.gallery.pick((res) => {
  316. this.chooseSuccessMethod(res.files, 0)
  317. }, function(e) {
  318. //console.log("取消选择图片");
  319. }, {
  320. filter: "image",
  321. multiple: true,
  322. maximum: maxNum
  323. });
  324. },
  325. chooseSuccessMethod(filePaths, type) {
  326. if (this.action == '') { //未配置上传路径
  327. this.$emit("chooseSuccess", filePaths, type); //filePaths 路径 type 0 为图片 1为视频
  328. } else {
  329. if (type == 1) {
  330. this.imgUpload(filePaths);
  331. } else {
  332. if (this.compress) { //设置了需要压缩
  333. this.imgCompress(filePaths);
  334. } else {
  335. this.imgUpload(filePaths);
  336. }
  337. }
  338. }
  339. },
  340. imgCompress(tempFilePaths) {
  341. uni.showLoading({
  342. title: '压缩中...'
  343. });
  344. let compressImgs = [];
  345. let results = [];
  346. tempFilePaths.forEach((item, index) => {
  347. compressImgs.push(new Promise((resolve, reject) => {
  348. // #ifndef H5
  349. uni.compressImage({
  350. src: item,
  351. quality: this.quality,
  352. success: res => {
  353. //console.log('compressImage', res.tempFilePath)
  354. results.push(res.tempFilePath);
  355. resolve(res.tempFilePath);
  356. },
  357. fail: (err) => {
  358. //console.log(err.errMsg);
  359. reject(err);
  360. },
  361. complete: () => {
  362. //uni.hideLoading();
  363. }
  364. })
  365. // #endif
  366. // #ifdef H5
  367. this.canvasDataURL(item, {
  368. quality: this.quality / 100
  369. }, (base64Codes) => {
  370. //this.imgUpload(base64Codes);
  371. results.push(base64Codes);
  372. resolve(base64Codes);
  373. })
  374. // #endif
  375. }))
  376. })
  377. Promise.all(compressImgs) //执行所有需请求的接口
  378. .then((results) => {
  379. uni.hideLoading();
  380. console.log('imgUpload', results)
  381. this.imgUpload(results);
  382. })
  383. .catch((res, object) => {
  384. uni.hideLoading();
  385. });
  386. },
  387. imgUpload(tempFilePaths) {
  388. // if (this.action == '') {
  389. // uni.showToast({
  390. // title: '未配置上传地址',
  391. // icon: 'none',
  392. // duration: 2000
  393. // });
  394. // return false;
  395. // }
  396. uni.showLoading({
  397. title: '上传中'
  398. });
  399. console.log('imgUpload', tempFilePaths)
  400. let uploadImgs = [];
  401. tempFilePaths.forEach((item, index) => {
  402. uploadImgs.push(new Promise((resolve, reject) => {
  403. console.log(index, item)
  404. const uploadTask = uni.uploadFile({
  405. url: this.action, //仅为示例,非真实的接口地址
  406. filePath: item,
  407. name: this.name,
  408. fileType: 'image',
  409. formData: this.formData,
  410. header: this.headers,
  411. success: (uploadFileRes) => {
  412. //uni.hideLoading();
  413. //console.log(typeof this.uploadSuccess)
  414. //console.log('')
  415. if (typeof this.uploadSuccess == 'function') {
  416. if (this.uploadSuccess(uploadFileRes).success) {
  417. this.value.push(this.uploadSuccess(uploadFileRes)
  418. .url)
  419. this.$emit("input", this.uploadLists);
  420. }
  421. }
  422. resolve(uploadFileRes);
  423. this.$emit("uploadSuccess", uploadFileRes);
  424. },
  425. fail: (err) => {
  426. console.log(err);
  427. //uni.hideLoading();
  428. reject(err);
  429. this.$emit("uploadFail", err);
  430. },
  431. complete: () => {
  432. //uni.hideLoading();
  433. }
  434. });
  435. }))
  436. })
  437. console.log("上传后:",this.uploadLists)
  438. Promise.all(uploadImgs) //执行所有需请求的接口
  439. .then((results) => {
  440. uni.hideLoading();
  441. })
  442. .catch((res, object) => {
  443. uni.hideLoading();
  444. this.$emit("uploadFail", res);
  445. });
  446. // uploadTask.onProgressUpdate((res) => {
  447. // //console.log('',)
  448. // uni.showLoading({
  449. // title: '上传中' + res.progress + '%'
  450. // });
  451. // if (res.progress == 100) {
  452. // uni.hideLoading();
  453. // }
  454. // });
  455. },
  456. canvasDataURL(path, obj, callback) {
  457. var img = new Image();
  458. img.src = path;
  459. img.onload = function() {
  460. var that = this;
  461. // 默认按比例压缩
  462. var w = that.width,
  463. h = that.height,
  464. scale = w / h;
  465. w = obj.width || w;
  466. h = obj.height || (w / scale);
  467. var quality = 0.8; // 默认图片质量为0.8
  468. //生成canvas
  469. var canvas = document.createElement('canvas');
  470. var ctx = canvas.getContext('2d');
  471. // 创建属性节点
  472. var anw = document.createAttribute("width");
  473. anw.nodeValue = w;
  474. var anh = document.createAttribute("height");
  475. anh.nodeValue = h;
  476. canvas.setAttributeNode(anw);
  477. canvas.setAttributeNode(anh);
  478. ctx.drawImage(that, 0, 0, w, h);
  479. // 图像质量
  480. if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
  481. quality = obj.quality;
  482. }
  483. // quality值越小,所绘制出的图像越模糊
  484. var base64 = canvas.toDataURL('image/jpeg', quality);
  485. // 回调函数返回base64的值
  486. callback(base64);
  487. }
  488. },
  489. }
  490. }
  491. </script>
  492. <style>
  493. .preview-full {
  494. position: fixed;
  495. top: 0;
  496. left: 0;
  497. bottom: 0;
  498. width: 100%;
  499. height: 100%;
  500. z-index: 1002;
  501. }
  502. .preview-full video {
  503. width: 100%;
  504. height: 100%;
  505. z-index: 1002;
  506. }
  507. .preview-full-close {
  508. position: fixed;
  509. right: 32rpx;
  510. top: 150rpx;
  511. width: 80rpx;
  512. height: 80rpx;
  513. line-height: 60rpx;
  514. text-align: center;
  515. z-index: 1003;
  516. /* background-color: #808080; */
  517. color: #fff;
  518. font-size: 65rpx;
  519. font-weight: bold;
  520. text-shadow: 1px 2px 5px rgb(0 0 0);
  521. }
  522. /* .preview-full-close-before,
  523. .preview-full-close-after {
  524. position: absolute;
  525. top: 50%;
  526. left: 50%;
  527. content: '';
  528. height: 60rpx;
  529. margin-top: -30rpx;
  530. width: 6rpx;
  531. margin-left: -3rpx;
  532. background-color: #FFFFFF;
  533. z-index: 20000;
  534. }
  535. .preview-full-close-before {
  536. transform: rotate(45deg);
  537. }
  538. .preview-full-close-after {
  539. transform: rotate(-45deg);
  540. } */
  541. .htz-image-upload-list {
  542. display: flex;
  543. flex-wrap: wrap;
  544. }
  545. .htz-image-upload-Item {
  546. /* width: 160rpx;
  547. height: 160rpx; */
  548. width: 205rpx;
  549. height: 205rpx;
  550. margin: 13rpx;
  551. border-radius: 10rpx;
  552. position: relative;
  553. }
  554. .htz-image-upload-Item image {
  555. width: 100%;
  556. height: 100%;
  557. border-radius: 10rpx;
  558. }
  559. .htz-image-upload-Item-video {
  560. width: 100%;
  561. height: 100%;
  562. border-radius: 10rpx;
  563. position: relative;
  564. }
  565. .htz-image-upload-Item-video-fixed {
  566. position: absolute;
  567. top: 0;
  568. left: 0;
  569. bottom: 0;
  570. width: 100%;
  571. height: 100%;
  572. border-radius: 10rpx;
  573. z-index: 996;
  574. }
  575. .htz-image-upload-Item video {
  576. width: 100%;
  577. height: 100%;
  578. border-radius: 10rpx;
  579. }
  580. .htz-image-upload-Item-add {
  581. font-size: 105rpx;
  582. /* line-height: 160rpx; */
  583. text-align: center;
  584. border: 1px dashed #d9d9d9;
  585. color: #d9d9d9;
  586. }
  587. .htz-image-upload-Item-del {
  588. background-color: #f5222d;
  589. font-size: 24rpx;
  590. position: absolute;
  591. width: 35rpx;
  592. height: 35rpx;
  593. line-height: 35rpx;
  594. text-align: center;
  595. top: 0;
  596. right: 0;
  597. z-index: 997;
  598. color: #fff;
  599. }
  600. .htz-image-upload-Item-del-cover {
  601. background-color: #f5222d;
  602. font-size: 24rpx;
  603. position: absolute;
  604. width: 35rpx;
  605. height: 35rpx;
  606. text-align: center;
  607. top: 0;
  608. right: 0;
  609. color: #fff;
  610. /* #ifdef APP-PLUS */
  611. line-height: 25rpx;
  612. /* #endif */
  613. /* #ifndef APP-PLUS */
  614. line-height: 35rpx;
  615. /* #endif */
  616. z-index: 997;
  617. }
  618. </style>