uniapp小程序上传图片并压缩

html >> template部分:

javascript 复制代码
<view class="mainBox">
	<uni-file-picker file-mediatype="image" mode="grid" limit="20" :value="uploadImgList"
		:sourceType="['camera', 'album']" @select="uploadSelect" ref="filePicker"
		@delete="uploadDelete"></uni-file-picker>
</view>

script >> methods部分:

javascript 复制代码
// 上传图片
uploadSelect(val) {
	val.tempFiles.forEach(async item => {
		try {
			// 压缩图片
			const compressedFilePath = await this.compressImage(item.url);
			// 将压缩后的图片转换为 Base64
			const base64Url = await this.becomeBase64img(compressedFilePath);
			this.uploadImgList.push({
				url: base64Url,
				uuid: item.uuid
			});
			this.imgBase64List.push(base64Url);
		} catch (error) {
			console.error('图片处理失败:', error);
		}
	})
},
// 压缩图片
compressImage(filePath) {
	return new Promise((resolve, reject) => {
		uni.compressImage({
			src: filePath,
			quality: 20, // 压缩质量,范围 0 - 100,数值越小,压缩率越高
			success: (res) => {
				resolve(res.tempFilePath);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
},
// 删除图片
uploadDelete(file) {
	for (let i = this.uploadImgList.length - 1; i >= 0; i--) {
		if (this.uploadImgList[i].uuid === file.tempFile.uuid) {
			this.uploadImgList.splice(i, 1);
			this.imgBase64List.splice(i, 1);
		}
	}
},
// 转义成base64图片
becomeBase64img(val) {
	return new Promise(function(resolve, reject) {
		pathToBase64(val).then(path => {
			resolve(path)
		}).catch(err => {
			reject(reject)
		})
	})
},		
相关推荐
说私域2 小时前
短视频私域流量池的变现路径创新:基于AI智能名片链动2+1模式S2B2C商城小程序的实践研究
大数据·人工智能·小程序
小溪彼岸3 小时前
uni-app小白从0开发一款鸿蒙Next应用到上线
uni-app·harmonyos
毕设源码-邱学长3 小时前
【开题答辩全过程】以 基于微信小程序的松辽律所咨询系统的设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
一颗小青松4 小时前
uniapp app端使用uniCloud的unipush
uni-app
+VX:Fegn08956 小时前
计算机毕业设计|基于springboot + vue物流配送中心信息化管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·小程序·课程设计
说私域6 小时前
B站内容生态下的私域流量运营创新:基于AI智能名片链动2+1模式与S2B2C商城小程序的融合实践
人工智能·小程序·流量运营
计算机毕设指导66 小时前
基于微信小程序的钓鱼论坛系统【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·maven
qq_12498707536 小时前
基于微信小程序的宠物交易平台的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·微信小程序·小程序·毕业设计·计算机毕业设计
cngm1108 小时前
uniapp+springboot后端跨域以及webview中cookie调试
spring boot·后端·uni-app
计算机毕设指导69 小时前
基于微信小程序的精致护肤购物系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea