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)
		})
	})
},		
相关推荐
游戏开发爱好者84 小时前
没有 Mac,如何上架 iOS App?多项目复用与流程标准化实战分享
android·ios·小程序·https·uni-app·iphone·webview
weixin_lynhgworld5 小时前
代驾小程序系统开发:引领出行行业数字化转型
小程序
Python大数据分析7 小时前
uniapp之微信小程序标题对其右上角按钮胶囊
微信小程序·小程序·uni-app
yzx9910138 小时前
JS与Go:编程语言双星的碰撞与共生
java·数据结构·游戏·小程序·ffmpeg
说私域11 小时前
基于开源链动2+1模式AI智能名片S2B2C商城小程序的私域流量池用户运营研究
人工智能·小程序·开源
zkmall11 小时前
小程序卡顿到丝滑体验:ZKmall开源商城性能优化与兼容修复实战指南
性能优化·小程序
CodeUp.11 小时前
校园二手交易小程序的设计与实现
小程序
菜鸟起航ing12 小时前
SaaS型小程序自动化发布解决方案
运维·小程序·自动化
awp25813 小时前
小程序安卓ApK转aab文件详情教程MacM4环境
android·小程序