uniapp 图片压缩上传 uni.chooseImage, uni.compressImage uni.upload

思路

  1. uni.chooseImage上传图片
  2. 判断图片的大小
  3. 如果超过了指定大小就使用 un,compressImage,将图片压缩

具体实现

  1. 上传文件返回一个 文件信息的数组list
  2. 创建一个承载promise的数组

  3. 循环 文件信息的数组,创建promise 如果文件的大小大于 2M 就使用 uni.compressImage压缩图片并将压缩的文件resolve出去,如果文件的大小小于2M 就直接将文件信息resolve返回出去

  4. 使用promise.all执行 promise数组 得到 压缩后的文件信息列表 compressList

  5. 调用upload方法

  6. 声明 promise数祖,循环 compressList 创建promise  调用 upload 上传图片,将上传后的图片resolve出去

  7. 使用promse.all 拿到 upload的线上文件信息,添加到最终的数据数组中,传递给后台保存或者渲染

	_chooseImg() {
			console.log('999');
			if (flag == true) {
				return;
			}
			let type_set = ['.png', '.jpg', '.jpeg'];
			uni.chooseImage({
				count: the.maxImg_ - the.imgPaths.length,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				extension: type_set,
				success: res => {
					console.log('res-chooseImg', res);
					let fileList = res.tempFiles;
					flag = true;
					if (fileList.length + the.imgPaths.length > the.maxImg_) {
						uni.showToast({
							title: `最多只能上传${the.maxImg_}个图片`,
							icon: 'none'
						});
						return;
					}
					let chooseList = res.tempFiles.map(ele=>ele.path)
					this.imgPaths= this.imgPaths.concat(chooseList)
					this.handleBeforeUpload(res.tempFiles);
				}
			});
		},
		// 图片上传
		imgUpload(tempFilePaths) {
			uni.showLoading({
				title: '上传中'
			});
			console.log('tempFilePaths', tempFilePaths);

			let uploadImgs = [];
			tempFilePaths.forEach((item, index) => {
				uploadImgs.push(
					new Promise((resolve, reject) => {
						console.log('item-000000000', item);
						let fileTypeList = item.split('.');
						let fileType = fileTypeList[fileTypeList.length - 1];
						let nowTime = new Date();
						let year = nowTime.getFullYear();
						let month = nowTime.getMonth() + 1;
						let day = nowTime.getDate();
						let time = nowTime.getTime();
						let filekey = `/img/${year}/${month}/${day}/${time}_${Math.floor(Math.random() * 100)}.${fileType}`;
						console.log('item-000000000filekey', filekey);
						let httpBase = {
							url: base.baseUrl + '/api/file/fileUpload',
							filePath: item,
							name: 'file',
							formData: {
								fileKey: filekey
							},
							header: {
								Authorization: this.handleToken()
							}
						};
						const uploadTask = uni.uploadFile({
							...httpBase,
							success: uploadFileRes => {
								console.log('uploadFileRes', uploadFileRes);
								flag = false;
								resolve(uploadFileRes);
							},
							fail: err => {
								console.log(err);
								flag = false;
								reject(err);
							},
							complete: () => {
								flag = false;
							}
						});
					})
				);
			});
			console.log("uploadImgs1111111111111111111111",uploadImgs)
			Promise.all(uploadImgs) //执行所有需请求的接口
				.then(results => {
					results.forEach(ele=>{
						let fileData = JSON.parse(ele.data).data
						this.resultImgPaths.push(fileData.fileUrl)
					})
					this.$emit("sendPic",this.resultImgPaths)
					uni.hideLoading();
				})
				.catch((res, object) => {
					uni.hideLoading();
				});
		},
	
handleToken() {
			let tokenC = uni.getStorageSync('token');
			return tokenC;
		},
		handleBeforeUpload(tempFilePaths) {
			uni.showLoading({
				title: '压缩中...'
			});
			let compressImgs = [];
			let results = [];
			let normalResults = [];
			tempFilePaths.forEach((item, index) => {
				console.log('item', item);
				let size = item.size / 1024 / 1024;
				if (size >= 1) {
					console.log("999999",size)
					compressImgs.push(
						new Promise((resolve, reject) => {
							uni.compressImage({
								src: item.path,
								quality: 60, // 仅对jpg有效
								success: res => {
									console.log('compressImage', res.tempFilePath);
									results.push(res.tempFilePath);
									resolve(res.tempFilePath);
								},
								fail: err => {
									reject(err);
								},
								complete: () => {}
							});
						})
					);
				} else {
					compressImgs.push(
						new Promise((resolve, reject) => {
							console.log("itemitem0000000000")
								results.push(item.path);
							resolve(item.path);
						})
					);
				}
			});
			console.log("compressImgs4444444444444444444",compressImgs)
			Promise.all(compressImgs) //执行所有需请求的接口
				.then(results => {
					console.log("results",results)
					uni.hideLoading();
					this.imgUpload(results);
				})
				.catch((res, object) => {
					uni.hideLoading();
				});
		},

你可能感兴趣的:(uniapp,实战,javascript,前端,vue.js)