基于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);
						},
					});
				});
			},
相关推荐
硕子鸽1 天前
UniApp + Dify 实战:详解 SSE 流式响应的解析与前端渲染
前端·uni-app·dify
2501_915918411 天前
iOS 项目中证书管理常见的协作问题
android·ios·小程序·https·uni-app·iphone·webview
Miketutu1 天前
[特殊字符] uni-app App 端实现文件上传功能(基于 xe-upload 插件)
前端·vue.js·uni-app
焚 城1 天前
uniapp 各种文件预览实现
vue.js·uni-app·html
weixin79893765432...1 天前
uni-app 全面深入的解读
uni-app
2501_915918411 天前
提升 iOS 应用安全审核通过率的一种思路,把容易被拒的点先处理
android·安全·ios·小程序·uni-app·iphone·webview
00后程序员张1 天前
APP如何快速上架Apple Store:完整上架流程与常见问题解析
android·小程序·https·uni-app·iphone·webview
ifeng09181 天前
uniapp开发鸿蒙:跨端兼容与条件编译实战
华为·uni-app·harmonyos
ifeng09181 天前
uniapp开发鸿蒙:常见问题与踩坑指南
华为·uni-app·harmonyos
2501_916008891 天前
iOS 应用发布流程中常被忽视的关键环节
android·ios·小程序·https·uni-app·iphone·webview