基于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 小时前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
Mr_li19 小时前
给 Vue 开发者的 uni-app 快速指南
vue.js·uni-app
anyup21 小时前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos
Mintopia2 天前
Vue3 项目如何迁移到 uni-app x:从纯 Web 到多端应用的系统指南
uni-app
Mintopia2 天前
uni-app x 发展前景技术分析:跨端统一的新阶段?
uni-app
不爱说话郭德纲3 天前
告别漫长的HbuilderX云打包排队!uni-app x 安卓本地打包保姆级教程(附白屏、包体积过大排坑指南)
android·前端·uni-app
HashTang4 天前
【AI 编程实战】第 12 篇:从 0 到 1 的回顾 - 项目总结与 AI 协作心得
前端·uni-app·ai编程
JunjunZ4 天前
uniapp 文件预览:从文件流到多格式预览的完整实现
前端·uni-app
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
TT_Close5 天前
“啪啪啪”三下键盘,极速拉起你的 uni-app 项目!
vue.js·uni-app·前端工程化