uni-app选择多张图片上传并压缩——2024.04.02

uni.chooseImage之后plus.zip.compressImage压缩

1、uni.uploadFile(OBJECT)只能循环调用上传(递归)

2、项目对图片压缩后的清晰度要求较高,不使用画布canvas压缩,chooseImage时选择原图。

javascript 复制代码
// 上传图片
chooseImage(){
	uni.chooseImage({
		sizeType: ['original'], //可以指定是原图还是压缩图,默认二者都有
		sourceType: ['album', 'camera'], //拍照
		// count: 1, //1张图
		success: (res) => {
			this.currentFiles = res.tempFilePaths;
			// 在上传某张图片之前压缩
			uni.showLoading({
				title: '照片压缩上传中',
				mask: true
			});
			// 第一张 之后递归
			this.translateapp(this.currentFiles[0], 0, imgUrl => {
				this.currentFiles[0] = imgUrl;
				this.uploadFile(0, imgUrl);
			})
			// 保存到相册
			// 如果是拍照则保存图片到相册
			// 相册选择的图片是以file://开头的绝对路径
			// 拍照返回的是以_doc/开头的相对路径
			var tempFilePaths = res.tempFilePaths[0];
			if (res.tempFilePaths.length == 1 && !tempFilePaths.startsWith('file://')) {
				uni.saveImageToPhotosAlbum({
					filePath: tempFilePaths,
					success: function() {
						console.log('save success');
					},
					fail(e) {
						uni.showToast({
							position: "bottom",
							icon: 'none',
							title: '保存图像到相册失败'
						})
					}
				});
			}
		},
		fail: (err) => {
			// #ifdef APP-PLUS
			// 安卓操作系统
			if(osName != 'ios'){
				if(err.code == 11){
					//用户点击取消
					return;
				}
				uni.showModal({
					title: '错误内容',
					content: '请确认相机权限已开启!',
					showCancel: false
				});
			}
			// #endif
		}
	})
},
// app端压缩图片
translateapp(img, i, callback) {
	plus.io.resolveLocalFileSystemURL(img, (entry) => { //通过URL参数获取目录对象或文件对象
		entry.file((file) => { // 可通过entry对象操作图片 
			console.log('压缩前图片信息:' + JSON.stringify(file)); //压缩前图片信息
			if (file.size > this.imgMaxLength) { //   如果大于imgMaxLength进行压缩
				this.scale = 50;
				plus.zip.compressImage({ // 5+ plus.zip.compressImage 了解一下,有详细的示例
					src: img, //src: 压缩原始图片的路径    
					dst: img.replace('.jpg', 'yasuo.jpg')
						.replace('.JPG', 'yasuo.JPG'),
					width: '100%', //dst: (String 类型 )压缩转换目标图片的路径,这里先在后面原始名后面加一个yasuo区分一下
					height: '100%', //width,height: (String 类型 )缩放图片的宽度,高度
					quality: this.scale, //quality: (Number 类型 )压缩图片的质量
					overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
					// format: 'jpg'   //format: (String 类型 )压缩转换后的图片格式
				}, (event) => {
					console.log('压缩后图片信息:' + JSON.stringify(event));
					callback(event.target);
				}, function(err) {
					console.log('Resolve file URL failed: ' + err.message);
					uni.showToast({
						title: err.message,
						icon: "none"
					})
				});
			} else { //else小于imgMaxLength跳过压缩,直接返回现有的src
				console.log('no resolve');
				// uni.hideLoading();
				callback(img);
			}
		});
	}, (e) => { // 返回错误信息
		console.log('Resolve file URL failed: ' + e.message);
		uni.showToast({
			title: e.message,
			icon: "none"
		})
	});
},
// 上传图片 递归函数 异步
uploadFile(i, file){
	var length = this.currentFiles.length;
	var that = this;
	var url = that.$commonData.uploadUrl[that.ProjectCode];
	uni.uploadFile({
		url: url,//上传的服务器地址
		filePath: file, //要上传文件资源的路径 String类型
		name: 'file',
		header:{
			"Authorization": 'Bearer ' + that.ACCESSTOKEN
		},
		success: function (res) { //当调用uploadFile成功之后,再次调用后台修改的操作
			if (res.statusCode == 200) {
				var responseData = JSON.parse(res.data);
				var item = {};
				if (responseData.result) {
					var Imghash = responseData.result[0].value;
					var type = that.uploadConfig.code;
					if (Imghash) {
						var fileItem = {
							attachmentId: Imghash,
							type: type,
						};
						that.attachmentList.push(fileItem);
					}
					i++;  //递归函数
					console.log('....第' + i + '张上传成功....');
					if (i < length){
						// 第一张 之后递归
						that.translateapp(that.currentFiles[i], i, imgUrl => {
							that.uploadFile(i, imgUrl);
						})
					}
					if (i == length){
						uni.hideLoading();
						uni.showToast({
							title: "图片上传成功",
							icon: "success"
						});
						// 上传attachmentList函数
						that.uploadImage();
					}
				}
			}else{
				uni.hideLoading();
				uni.showToast({
					title: res.data.error.message,
					icon: 'none',
				});
			}
		},
		fail: (err) => {
			uni.hideLoading();
			uni.showToast({
				title: '图片上传失败',
				duration: 2000,
				icon: "none" ,
			});
		}
	});
},
相关推荐
00后程序员张18 小时前
iOS 上架费用全解析 开发者账号、App 审核、工具使用与开心上架(Appuploader)免 Mac 成本优化指南
android·macos·ios·小程序·uni-app·cocoa·iphone
前端与小赵1 天前
uni-app开发安卓app时控制屏幕常亮不息屏
android·gitee·uni-app
2501_916008891 天前
HTTPS 请求抓包,从原理到落地排查的工程化指南(Charles / tcpdump / Wireshark / Sniffmaster)
ios·小程序·https·uni-app·wireshark·iphone·tcpdump
xiaohe06011 天前
🥳 Uni ECharts 2.1 发布:正式支持鸿蒙,零成本迁移、全平台兼容、跨端开发零负担!
vue.js·uni-app·echarts
2501_915909062 天前
WebView 调试工具全解析,解决“看不见的移动端问题”
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 天前
App 怎么上架 iOS?从准备资料到开心上架(Appuploader)免 Mac 上传的完整实战流程指南
android·macos·ios·小程序·uni-app·iphone·webview
行走的陀螺仪2 天前
uni-app + Vue3 实现折叠文本(超出省略 + 展开收起)
前端·javascript·css·uni-app·vue3
小禾青青2 天前
uniapp安卓打包遇到报错:Uncaught SyntaxError: Invalid regular expression: /[\p{L}\p{N}]/
android·uni-app
环信即时通讯云2 天前
实现小程序 uniApp 输入框展示自定义表情包
小程序·uni-app
2501_915921432 天前
iOS 抓不到包怎么办?工程化排查与替代抓包方案(抓包/HTTPS/Charles代理/tcpdump)
android·ios·小程序·https·uni-app·iphone·tcpdump