uniapp小程序上传图片并压缩

发布于:2025-07-26 ⋅ 阅读:(15) ⋅ 点赞:(0)

html >> template部分:

<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部分:

// 上传图片
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)
		})
	})
},		

网站公告

今日签到

点亮在社区的每一天
去签到