基于uniapp开发的微信H5图片上传压缩

安装Compressor,并在页面引入

复制代码
npm i compressorjs

	import Compressor from "compressorjs"

具体使用代码

H5部分:

html 复制代码
<view class="h5upload" @click="add">
								<view class="">
									+
								</view>
								<view class="">
									上传图片
								</view>
							</view>

js部分:

javascript 复制代码
//选择图片
			async add() {
				const input = document.createElement('input');
				input.type = 'file';
				input.accept = 'image/*';
				input.multiple = true;

				input.onchange = async (event) => {
					const files = Array.from(event.target.files);
					let arr = [];
					let promiseArr = [];
					uni.showLoading({
						title: "上传中"
					});

					for (const file of files) {
						try {
							const compressedBlob = await this.compressImage(file);
							console.log("图片压缩后", compressedBlob);

							// 将 Blob 转换为 File 对象
							const fileName = file.name; // 保持原文件名
							const fileType = compressedBlob.type; // 获取 Blob 类型
							const fileToUpload = new File([compressedBlob], fileName, {
								type: fileType
							});

							// 使用 FormData 来上传文件
							const formData = new FormData();
							formData.append('file', fileToUpload);
							formData.append('user', 'test');

							promiseArr.push(fetch(`${IMG_BASE_URL}/photo_album`, {
									method: 'POST',
									body: formData,
								})
								.then(response => {
									if (!response.ok) {
										throw new Error(`网络错误: ${response.status}`);
									}
									return response.json();
								})
								.then(data => {
									console.log("上传响应数据:", data);
									return data?.data?.path || "";
								})
								.catch(error => {
									console.error("上传失败", error);
									throw error;
								}));
						} catch (error) {
							console.error("压缩失败", error);
						}
					}

					const results = await Promise.all(promiseArr);
					console.log("上传图片数组", results);
					uni.hideLoading();
					this.fileList = [...this.fileList, ...results]
				};

				input.click();
			},
    //压缩
	compressImage(file) {
				return new Promise((resolve, reject) => {
					new Compressor(file, {
						quality: 0.7,//压缩等级
						success(result) {
							resolve(result);
						},
						error(err) {
							reject(err);
						},
					});
				});
			},
相关推荐
木易 士心2 小时前
Uni-App 实现多身份动态切换 TabBar 指南
uni-app
2501_9151063219 小时前
CDN 可以实现 HTTPS 吗?实战要点、部署模式与真机验证流程
网络协议·http·ios·小程序·https·uni-app·iphone
LoveEate2 天前
uniapp 运行/发版微信小程序
微信小程序·小程序·uni-app
fakaifa2 天前
【高级版】沃德政务招商系统源码+uniapp小程序
小程序·uni-app·源码下载·沃德政务招商系统·招商系统源码
weixin_446938872 天前
uniapp vue-i18n如何使用
前端·vue.js·uni-app
有来技术2 天前
UniApp 自定义导航栏适配指南:微信小程序胶囊遮挡、H5 与 App 全端通用方案
微信小程序·uni-app
卷Java3 天前
违规通知功能修改说明
java·数据库·微信小程序·uni-app
卷Java3 天前
用户权限控制功能实现说明
java·服务器·开发语言·数据库·servlet·微信小程序·uni-app
王佳斌4 天前
sass变量默认
uni-app
二饭4 天前
uniapp与webview通信
uni-app