安装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);
},
});
});
},