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)
		})
	})
},		
相关推荐
游戏开发爱好者85 小时前
iOS应用加固方案全解析:源码加固与IPA在线加固对比
android·macos·ios·小程序·uni-app·cocoa·iphone
满栀5856 小时前
uni-app 小程序开发实战:从路由踩坑、数据对接到 UI 优化的全方位复盘
ui·uni-app·notepad++
2301_8103131816 小时前
宠物服务APP开发宠物社交上门喂养洗护商城系统源码搭建
小程序·团队开发·软件需求·宠物
momodira81 天前
防溺水作品投票小程序选哪个?
小程序·投票工具·线上制作教程
鲁Q同志1 天前
微信小程序【uni-file-picker文件预览】
微信小程序·小程序
他叫自己MR张1 天前
uni-app 应用启动报uni-ad业务状态异常(-9002)【已解决】
uni-app
2601_963869951 天前
【计算机毕业设计】基于微信小程序的拼车服务系统设计与实现
微信小程序·小程序·课程设计
2501_915909061 天前
iOS应用性能监控 Instruments工具与崩溃日志分析完整指南
android·ios·小程序·https·uni-app·iphone·webview
人脸核身安全官1 天前
人脸核身SDK接入实测:H5/小程序常见兼容问题与通过率优化
小程序·人脸识别·人脸比对·活体检测·实人认证·h5人脸核验·旷视
2501_915918412 天前
详解iOS App上架至App Store的全流程步骤与注意事项
android·macos·ios·小程序·uni-app·cocoa·iphone