跳到主要内容

表单中图片上传并压缩

本案例来自三方开发者「页一」

1. 使用场景

当我们上传的图片很大时,且需要进行一定的压缩以达到节约宜搭附件容量的情况下,可参考本例。

2. 实现功能

2.1 引入JS资源并关闭上传图片组件的自动上传

// 当页面渲染完毕后马上调用下面的函数,这个函数是在当前页面 - 设置 - 生命周期 - 页面加载完成时中被关联的。
export function didMount() {
// 关闭自动上传,需要压缩图片的图片上传组件都需要关闭自动上传
this.$('imageField_l7zmi4nk').set('autoUpload', false); // 图片压缩One
this.$('imageField_lhg0ipwp').set('autoUpload', false); // 图片压缩Two
this.utils.loadScript('https://g.alicdn.com/code/lib/compressorjs/1.1.1/compressor.min.js'); // 资源引入,无需修改
}

2.2 配置表单页面

2.3 将下面代码拷贝至页面JS中

// 图片压缩One
export function onSelectFileOne(files) {
this.poptoastLoading('图片压缩中', 100);
this.imgCompressor('imageField_l7zmi4nk', files);
}

// 图片压缩Two
export function onSelectFileTwo(files) {
this.poptoastLoading('图片压缩中', 100);
this.imgCompressor('imageField_lhg0ipwp', files);
}

// 下述代码都不需要修改
export function onImgSuccess() {
this.onCloseLoading();
};

export function imgCompressor(selectedField = '', files = []) {
const selectedFD = this.$(selectedField);
const selectedType = this.$(selectedField).get("type");
const isMobile = this.utils.isMobile()
files.forEach(fileItem => {
const reader = new FileReader();
reader.onload = () => {
const file = dataURL2Blob2File(reader.result, fileItem);
if (!file) {
return;
}
new Compressor(file, {
quality: 0.2, // 压缩率,想修改要锁比例,只要修改这个参数即可
maxWidth: 1800, // 最大宽度
maxHeight: 1400,// 最大高度
mimeType: 'image/jpeg',
success(result) {
const formData = new FormData();
result.lastModifiedDate = new Date();
result.name = fileItem.name;
result.uid = fileItem.uid;
let uploaderRef = null;
if (selectedType === "drag") {
uploaderRef = selectedFD.uploaderRef.uploaderRef;
} else {
uploaderRef = isMobile ? selectedFD.uploaderRef.uploaderRef : selectedFD.uploaderRef;
}
if (uploaderRef.state.value) {
uploaderRef.state.value.forEach(_file => {
if (_file && _file.uid === file.uid) {
_file.size = result.size;
}
});
}
uploaderRef.uploaderRef.startUpload([result]);
},
error(err) {
selectedFD.setValue({});
console.log(err.message);
},
});
};
reader.readAsDataURL(fileItem.originFileObj);
})
};

function dataURL2Blob2File(dataURL, file) {
const arr = dataURL.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
u8arr = new Uint8Array(bstr.length);
let n = bstr.length;
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
const blob = new Blob([u8arr], { type: mime });
blob.lastModifiedDate = new Date();
blob.name = file.name;
blob.uid = file.uid;
return blob;
}

let closeLoading;
export function poptoastLoading(title_str, s) {
closeLoading = this.utils.toast({
title: title_str,
type: 'loading',
size: "large"
});
if (s != 0) {
setTimeout(() => {
this.onCloseLoading();
}, s * 1000);
}
};

export function onCloseLoading() {
if (closeLoading) {
closeLoading();
}
};

2.4 图片上传组件动作绑定

3. 实现效果

附件下载:

4. 在线试玩

Copyright © 2024钉钉(中国)信息技术有限公司和/或其关联公司浙ICP备18037475号-4