htz-image-upload.vue 15.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
<template>
	<view class="htz-image-upload-list">
		<u-line-progress v-if="ifvideo" :striped="true" :striped-active="true" active-color="#19BE6B" height="16" :percent="percent"></u-line-progress>
		<view class="htz-image-upload-Item" v-if="uploadType == 'image'" v-for="(item,index) in uploadLists"
			:key="index">
			<image :src="imgUrl + item" @click="imgPreview(index)"></image>
			<view class="htz-image-upload-Item-del" v-if="remove" @click="imgDel(index)">×</view>
		</view>
		<view class="htz-image-upload-video" v-if="uploadType == 'video'" v-for="(item,index) in uploadLists"
			:key="index">
			<video :id="'video_'+index" :src="imgUrl + item" :data-index="index" :controls="true"
				:enable-play-gesture="true" objectFit="contain"></video>
			<view class="delBtn">
				<view class="btn" @click="videoDel(index)">
					删除
				</view>
			</view>
		</view>
		<view class="htz-image-upload-Item htz-image-upload-Item-add" v-if="uploadLists.length<max" @click="imgAdd">
			+
		</view>
	</view>
</template>

<script>
	export default {
		name: 'htz-image-upload',
		props: {
			/* max: { //展示图片最大值
				type: Number,
				default: 9,
			}, */
			chooseNum: { //选择图片数
				type: Number,
				default: 9,
			},
			name: { //发到后台的文件参数名
				type: String,
				default: 'file',
			},
			remove: { //是否展示删除按钮
				type: Boolean,
				default: true,
			},
			sourceType: { //选择照片来源 【ps:H5就别费劲了,设置了也没用。不是我说的,官方文档就这样!!!】
				type: Array,
				default: () => ['album', 'camera'],
			},
			headers: { //上传的请求头部
				type: Object,
				default: () => {},
			},
			formData: { //HTTP 请求中其他额外的 form data
				type: Object,
				default: () => {},
			},
			compress: { //是否需要压缩
				type: Boolean,
				default: true,
			},
			quality: { //压缩质量,范围0~100
				type: Number,
				default: 80,
			},
			imagesEdit: { //受控图片列表
				type: Array
			},
			videoEdit: {
				type: String,
				default: ''
			},
			uploadSuccess: {
				default: (res) => {
					return {
						success: false,
						url: ''
					}
				},
			},
			pgType: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				ifvideo:false,
				percent:0,
				uploadType: '',
				uploadLists: [],
				imgUrl: this.imgUrl,
				max: 1
			}
		},
		mounted() {
			console.log(this.imagesEdit, this.videoEdit)
			if (this.imagesEdit.length > 0) {
				this.uploadType = 'image'
				this.max = 9
				this.uploadLists = this.imagesEdit;
			}
			if (this.videoEdit != '') {
				this.uploadType = 'video'
				
				this.uploadLists.push(this.videoEdit);
			}
		},
		watch: {
			value(val, oldVal) {
				this.uploadLists = val
			}
		},
		methods: {
			/* videoPlay(e) {
				let index = e.currentTarget.dataset.index;
				// 获取 video 上下文 videoContext 对象
                let videoContext = uni.createVideoContext('video_'+index);
                // 进入全屏状态
                videoContext.requestFullScreen();
			}, */
			imgDel(index) {
				uni.showModal({
					title: '提示',
					content: '您确定要删除么?',
					success: (res) => {
						if (res.confirm) {
							let delUrl = this.uploadLists[index]
							this.uploadLists.splice(index, 1)
							this.$emit("changeImage", this.uploadLists);
						} else if (res.cancel) {}
					}
				});
			},
			videoDel(index) {
				uni.showModal({
					title: '提示',
					content: '您确定要删除么?',
					success: (res) => {
						if (res.confirm) {
							
							this.uploadLists.splice(index, 1)
							this.$emit("changeVideo", this.uploadLists);
							this.percent = 0
							this.ifvideo = false
						} else if (res.cancel) {}
					}
				});
			},
			imgPreview(index) {
				let imgPreview = []
				this.uploadLists.forEach((item) => {
					imgPreview.push(this.imgUrl + item)
				})
				uni.previewImage({
					urls: imgPreview,
					current: index,
					loop: true
				});
			},
			imgAdd() {
				// 视频上传中不允许触发第二次
				if(this.ifvideo) {
					return
				}
				let nowNum
				let thisNum
				if (this.pgType == '' && (this.uploadType == '' || this.uploadLists.length == 0)) {
					uni.showActionSheet({
						itemList: ['选择图片', '选择视频'],
						success: (res) => {
							if (res.tapIndex == 0) {
								this.uploadType = 'image'
								this.max = 9
								nowNum = Math.abs(this.uploadLists.length - this.max);
								thisNum = (this.chooseNum > nowNum ? nowNum : this.chooseNum) //可选数量
								this.$emit('changeType', 1)
								this.chooseImage(thisNum)
								this.ifvideo = false
							} else if (res.tapIndex == 1) {
								this.uploadType = 'video'
								this.max = 1
								this.$emit('changeType', 2)
								// this.chooseVideo(thisNum)
								this.ifvideo = true
							}
						},
						fail: (res) => {
							console.log(res.errMsg);
							this.ifvideo = false
						}
					});
				} else if (this.pgType == 'uploadImg' || this.uploadType == 'image') {
					this.max = 9
					nowNum = Math.abs(this.uploadLists.length - this.max);
					thisNum = (this.chooseNum > nowNum ? nowNum : this.chooseNum) //可选数量
					this.uploadType = 'image'
					this.chooseImage(thisNum)
				} else {
					this.chooseVideo(thisNum)
				}
			},
			chooseVideo(thisNum) {
				uni.chooseVideo({
					count: thisNum,
					compressed: false,
					sourceType: ['camera', 'album'],
					success: (res) => {
						/* if(res.size/(1024*1024) > 100){
							uni.showToast({
								title:'视频大小大于100M,请重新选择',
								icon:'none'
							})
							return
						}else{ */
						// uni.showLoading({
						// 	title:'上传中...'
						// })
					
						let filePath = res.tempFilePath
						console.log(filePath)
						console.log(filePath.lastIndexOf('.'))
						console.log(filePath.length)
						console.log(filePath.substr(filePath.lastIndexOf('.'), filePath.length))
						// #ifdef APP-PLUS
						let suffix = filePath.substr(filePath.lastIndexOf('.'), filePath.length)
						// #endif
						// #ifndef APP-PLUS
						let suffix = res.name.substr(res.name.lastIndexOf('.'), res.name.length)
						// #endif
						//获取七牛云token
						uni.request({
							url: this.apiUrl + '/common/getQiniuToken',
							method: 'POST',
							success: (qiniuRet) => {
								const uploadTask = uni.uploadFile({
									url: 'https://up-z2.qiniup.com',
									filePath: filePath,
									name: 'file',
									formData: {
										'key': qiniuRet.data.data.key + suffix,
										'token': qiniuRet.data.data.token
									},
									success: (uploadFileRes) => {
										console.log('上传七牛云结果', JSON.parse(uploadFileRes
											.data))
										uni.hideLoading()
										this.uploadLists.push('/' + JSON.parse(
											uploadFileRes.data).key)
										this.$emit("changeVideo", this.uploadLists);
									},
									fail: (err) => {
										uni.hideLoading()
										uni.showToast({
											title: "上传七云牛错误",
											icon: 'none'
										})
										console.log('上传七牛云报错', err)
									}
								});
								uploadTask.onProgressUpdate((res)=> {
									this.percent = res.progress;
									// console.log('上传进度' + res.progress);
									// console.log('已经上传的数据长度' + res.totalBytesSent);
									// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
								});

							},

						})

						/* let filePath = res.tempFilePath
						uni.uploadFile({
							url: this.apiUrl + '/common/upload', //仅为示例,非真实的接口地址
							filePath: filePath,
							timeout: 300000,
							header: {
								'token': uni.getStorageSync('token')
							},
							name: 'file',
							formData: {
								'user': 'test'
							},
							success: (uploadFileRes) => {
								uni.hideLoading()
								console.log('上传文件',JSON.parse(uploadFileRes.data));
								if(JSON.parse(uploadFileRes.data).code == 1){
									this.uploadLists.push(JSON.parse(uploadFileRes.data).data.url)
									this.$emit("changeVideo", this.uploadLists);
								}else{
									uni.showToast({
										title:JSON.parse(uploadFileRes.data).msg,
										icon:'none'
									})
								}
							}
						}); */
						// }
					},
				})
			},
			chooseImage(thisNum) {
				// #ifdef APP-PLUS
				if (this.sourceType.length > 1) {
					uni.showActionSheet({
						itemList: ['拍摄', '从手机相册选择'],
						success: (res) => {
							if (res.tapIndex == 1) {
								this.appGallery(thisNum);
							} else if (res.tapIndex == 0) {
								this.appCamera();
							}
						},
						fail: (res) => {
							console.log(res.errMsg);
						}
					});
				}
				if (this.sourceType.length == 1 && this.sourceType.indexOf('album') > -1) {
					this.appGallery(thisNum);
				}

				if (this.sourceType.length == 1 && this.sourceType.indexOf('camera') > -1) {
					this.appCamera();
				}
				// #endif
				//#ifndef APP-PLUS
				uni.chooseImage({
					count: thisNum,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
					sourceType: this.sourceType,
					success: (res) => {
						this.chooseSuccessMethod(res.tempFilePaths)
						//console.log('tempFiles', res)
						// if (this.action == '') { //未配置上传路径
						// 	this.$emit("chooseSuccess", res.tempFilePaths);
						// } else {
						// 	if (this.compress && (res.tempFiles[0].size / 1024 > 1025)) { //设置了需要压缩 并且 文件大于1M,进行压缩上传
						// 		this.imgCompress(res.tempFilePaths);
						// 	} else {
						// 		this.imgUpload(res.tempFilePaths);
						// 	}
						// }
					}
				});
				// #endif
			},
			appCamera() {
				var cmr = plus.camera.getCamera();
				var res = cmr.supportedImageResolutions[0];
				var fmt = cmr.supportedImageFormats[0];
				//console.log("Resolution: " + res + ", Format: " + fmt);
				cmr.captureImage((path) => {
						//alert("Capture image success: " + path);
						this.chooseSuccessMethod([path])
					},
					(error) => {
						//alert("Capture image failed: " + error.message);
						console.log("Capture image failed: " + error.message)
					}, {
						resolution: res,
						format: fmt
					}
				);
			},
			appGallery(maxNum) {
				plus.gallery.pick((res) => {
					this.chooseSuccessMethod(res.files)
				}, function(e) {
					//console.log("取消选择图片");
				}, {
					filter: "image",
					multiple: true,
					maximum: maxNum
				});
			},
			chooseSuccessMethod(filePaths) {
				if (this.compress) { //设置了需要压缩 
					this.imgCompress(filePaths);
				} else {
					this.imgUpload(filePaths);
				}
			},
			imgCompress(tempFilePaths) {
				uni.showLoading({
					title: '压缩中...'
				});

				let compressImgs = [];
				let results = [];
				tempFilePaths.forEach((item, index) => {
					compressImgs.push(new Promise((resolve, reject) => {
						// #ifndef H5
						uni.compressImage({
							src: item,
							quality: this.quality,
							success: res => {
								//console.log('compressImage', res.tempFilePath)
								results.push(res.tempFilePath);
								resolve(res.tempFilePath);
							},
							fail: (err) => {
								//console.log(err.errMsg);
								reject(err);
							},
							complete: () => {
								//uni.hideLoading();
							}
						})
						// #endif
						// #ifdef H5
						this.canvasDataURL(item, {
							quality: this.quality / 100
						}, (base64Codes) => {
							//this.imgUpload(base64Codes);
							results.push(base64Codes);
							resolve(base64Codes);
						})
						// #endif
					}))
				})
				Promise.all(compressImgs) //执行所有需请求的接口
					.then((results) => {
						uni.hideLoading();
						this.imgUpload(results);
					})
					.catch((res, object) => {
						uni.hideLoading();
					});
			},
			imgUpload(tempFilePaths) {
				uni.showLoading({
					title: '上传中'
				});
				let uploadImgs = [];
				tempFilePaths.forEach((item, index) => {
					uploadImgs.push(new Promise((resolve, reject) => {
						const uploadTask = uni.uploadFile({
							url: this.apiUrl + '/common/upload', //仅为示例,非真实的接口地址
							filePath: item,
							name: this.name,
							fileType: 'image',
							formData: this.formData,
							header: {
								'token': uni.getStorageSync('token')
							},
							success: (uploadFileRes) => {
								console.log('上传图片', uploadFileRes)
								if (JSON.parse(uploadFileRes.data).code == 1) {
									this.uploadLists.push(JSON.parse(uploadFileRes.data)
										.data.url)
									this.$emit("changeImage", this.uploadLists);
								} else {
									uni.showToast({
										title: JSON.parse(uploadFileRes.data).msg,
										icon: 'none'
									})
								}
								resolve(uploadFileRes);
							},
							fail: (err) => {
								console.log(err);
								//uni.hideLoading();
								reject(err);
								this.$emit("uploadFail", err);
							},
							complete: () => {
								//uni.hideLoading();
							}
						});
					}))
				})
				Promise.all(uploadImgs) //执行所有需请求的接口
					.then((results) => {
						uni.hideLoading();
					})
					.catch((res, object) => {
						uni.hideLoading();
						this.$emit("uploadFail", res);
					});
			},
			canvasDataURL(path, obj, callback) {
				var img = new Image();
				img.src = path;
				img.onload = function() {
					var that = this;
					// 默认按比例压缩
					var w = that.width,
						h = that.height,
						scale = w / h;
					w = obj.width || w;
					h = obj.height || (w / scale);
					var quality = 0.8; // 默认图片质量为0.8
					//生成canvas
					var canvas = document.createElement('canvas');
					var ctx = canvas.getContext('2d');
					// 创建属性节点
					var anw = document.createAttribute("width");
					anw.nodeValue = w;
					var anh = document.createAttribute("height");
					anh.nodeValue = h;
					canvas.setAttributeNode(anw);
					canvas.setAttributeNode(anh);
					ctx.drawImage(that, 0, 0, w, h);
					// 图像质量
					if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
						quality = obj.quality;
					}
					// quality值越小,所绘制出的图像越模糊
					var base64 = canvas.toDataURL('image/jpeg', quality);
					// 回调函数返回base64的值
					callback(base64);
				}
			},
		}
	}
</script>

<style>
	.htz-image-upload-list {
		display: flex;
		flex-wrap: wrap;
	}

	.htz-image-upload-Item {
		width: 150rpx;
		height: 150rpx;
		margin: 32rpx 0 0 32rpx;
		border-radius: 10rpx;
		position: relative;
	}

	.htz-image-upload-Item image {
		width: 100%;
		height: 100%;
		border-radius: 10rpx;
	}

	.htz-image-upload-video {
		width: 750rpx;
		height: 450rpx;
	}

	.htz-image-upload-video video {
		width: 100%;
		height: 400rpx;
	}

	.delBtn {
		display: flex;
		justify-content: center;
	}

	.delBtn .btn {
		font-size: 28rpx;
		text-align: center;
		background: #f5222d;
		width: 100rpx;
		height: 50rpx;
		line-height: 50rpx;
		color: #fff;
		border-radius: 50rpx;
	}

	.htz-image-upload-Item-add {
		font-size: 105rpx;
		/* line-height: 160rpx; */
		text-align: center;
		border: 1px dashed #d9d9d9;
		color: #d9d9d9;
	}

	.htz-image-upload-Item-del {
		background-color: #f5222d;
		font-size: 24rpx;
		position: absolute;
		width: 35rpx;
		height: 35rpx;
		line-height: 35rpx;
		text-align: center;
		top: 0;
		right: 0;
		z-index: 100;
		color: #fff;
	}
</style>