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)
		})
	})
},		
相关推荐
汝生淮南吾在北1 天前
SpringBoot3+Vue3小区物业报修系统+微信小程序
微信小程序·小程序·vue·毕业设计·springboot·课程设计·毕设
汤姆yu1 天前
基于微信小程序的自习室座位预约系统
微信小程序·小程序
2501_915106321 天前
HTTP 协议详解,HTTP 协议在真实运行环境中的表现差异
网络·网络协议·http·ios·小程序·uni-app·iphone
焦糖玛奇朵婷1 天前
扭蛋机小程序:线上扭蛋机模式发展新形势[特殊字符]
大数据·数据库·程序人生·小程序·软件需求
咸虾米_1 天前
开发uniapp前端通用价格组件提交到DCloud插件市场
uni-app·商城·开发插件·dcloud插件市场·扩展组件
郑州光合科技余经理1 天前
实战分享:如何构建东南亚高并发跑腿配送系统
java·开发语言·javascript·spring cloud·uni-app·c#·php
云云只是个程序马喽1 天前
海外短剧系统开发核心功能设计及上线材料准备
小程序·php
2501_916007471 天前
iOS与Android符号还原服务统一重构实践总结
android·ios·小程序·重构·uni-app·iphone·webview
全栈软件开发1 天前
最新壁纸头像小程序系统源码 带流量主
小程序
嘿siri1 天前
uniapp enter回车键不触发消息发送,已解决
前端·前端框架·uni-app·vue