表单中 / 自定义页面中图片裁剪后上传
本案例来自来自三方开发者「冯鹏」
1. 使用场景
当我们上传的图片需要做一些裁剪处理时,可参考本例。
2. 实现功能
下述操作除了对话框需要从自定义页面复制到表单页面,其余操作表单 / 自定义页面相同。
2.1 引入三方JS资源和CSS资源

this.utils.loadStyleSheet('https://g.alicdn.com/yida-platform/react-cropper/1.0.0/css/react-cropper.css');
this.utils.loadScript('https://g.alicdn.com/yida-platform/react-cropper/1.0.0/js/react-cropper.js');
2.2 配置表单 / 自定义页面
注意关闭自动上传。

2.3 配置用到的变量

2.4 配置裁剪用到的对话框

JSX组件内代码如下:
function render() {
return(
<window.ReactCropper
ref={this.saveCropperrRef.bind(this)}
src={this.state.src}
style={{ height: 300, width: 400 }}
/>
);
}
对话框事件绑定:

OnOk事件代码如下:
注意修改第4行中的图片上传组件唯一标识和第14行中的对话框组件唯一标识。
export function onOk() {
const data = this.state.cropperRef.cropper.getCroppedCanvas().toDataURL();
const file = dataURL2Blob2File(data, this.state.file);
let uploaderRef = this.utils.isMobile() ? this.$('imageField_l9ozo0n1').uploaderRef.uploaderRef : this.$('imageField_l9ozo0n1').uploaderRef;
console.log('file', file);
if (uploaderRef.state.value) {
uploaderRef.state.value.forEach(_file => {
if (_file && _file.uid === file.uid) {
_file.size = file.size;
}
});
}
uploaderRef.uploaderRef.startUpload([file]);
this.$('dialog_kqby9wqe').hide();
}
2.5 将下面代码拷贝至页面JS中
注意将18行的对话框组件唯一标识。
export function onSuccess(file, value) {
this.utils.toast({
title: '上传成功'
});
}
/**
* imageField onSelect
*/
export function onSelect(files) {
console.log('onSelect');
const reader = new FileReader();
reader.onload = () => {
this.setState({
src: reader.result,
file: files[0],
});
this.$('dialog_kqby9wqe').show();
};
reader.readAsDataURL(files[0].originFileObj);
}
/**
* 图片剪切开始
*/
export function saveCropperrRef(ref) {
this.setState({
cropperRef: ref,
});
}
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 to File
// set lastModifiedDate and name
blob.lastModifiedDate = new Date();
blob.name = file.name;
blob.uid = file.uid;
return blob;
}
2.6 图片上传组件动作绑定

3. 实现效果

4. 在线试玩
本文档对您是否有帮助?