先上效果图
import { Upload, Button, Modal } from 'antd';
state:
imgList: [], // 图片
avatarModalVisible: false,
avatarConfirmLoading: false,
render:
const {
imgList,
avatarModalVisible,
avatarConfirmLoading,
} = this.state;
<>
{imgList.length !== 0 && (
<Upload
action=""
listType="picture-card"
fileList={imgList}
onRemove={this.onRemove}
/>
)}
{imgList.length < 9 && (
<Button onClick={() => this.hanldeUpload()}>上传图片</Button>
)}
</>
<Modal
title="设备图片"
visible={avatarModalVisible}
onOk={this.handleOk}
onCancel={this.handleCancel}
confirmLoading={avatarConfirmLoading}
>
<div>
<Cropper
style={{ width: 300, height: 200 }}
orginStyle={{ width: 300, height: 200 }}
hidePreview
hideInput
hideRatioBtn
hideTailorBtn
aspectRatio={1 / 1}
src=""
handleTailor={cb => {
this.handleTailor = cb;
}}
autoCropArea={0.95}
ref={el => (this.cropperRef = el)}
isUpload
minContainerWidth={300}
minContainerHeight={200}
/>
</div>
</Modal>
方法:
// 弹窗取消
handleCancel = () => {
this.setState({
avatarModalVisible: false,
});
};
// 弹窗确定
handleOk = e => {
const file = base64ConvertFile(this.handleTailor(), createUuid());
const uuid = createUuid();
const params = {
uuid,
file,
type: 1,
};
// 调用接口
this.queryZuulDocrepoUploadPost(params);
};
// 图片上传
queryZuulDocrepoUploadPost = params => {
const fileDocDownloadPath = 'api/download?attachmentId=';
const { imgList } = this.state;
this.setState(
{
avatarConfirmLoading: true,
},
async () => {
const formData = new FormData();
// 将得到的文件流添加到FormData对象
formData.append('file', params.file);
formData.append('uuid', params.uuid);
formData.append('type', params.type);
const res = await axios.post(`api/upload`, formData);
this.setState(
{
avatarConfirmLoading: false,
imgList: [
...imgList,
{
uid: params.uuid,
name: res?.data?.data?.fjmc,// 文件名称
url: fileDocDownloadPath + res?.data?.data?.bh, // 图片的src设置
},
],
},
() => {
this.setState({
avatarModalVisible: false,
});
}
);
}
);
};
// 打开剪裁弹窗
hanldeUpload = () => {
this.setState({
avatarModalVisible: true,
});
};
// 删除图片
onRemove = file => {
let { imgList } = this.state;
imgList = imgList.filter(item => item.uid !== file.uid);
this.setState({
imgList,
});
};
base64ConvertFile = function(urlData, filename) {
if (typeof urlData !== 'string') {
// ("urlData不是字符串")
return;
}
const arr = urlData.split(',');
const type = arr[0].match(/:(.*?);/)[1];
const fileExt = type.split('/')[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], `${filename}.${fileExt}`, {
type,
});
};