import React, { useState, Fragment, useMemo } from 'react';
import { Upload, Modal, Progress } from 'antd';
import { proxyDCIMAPI } from '@/services/proxyAPI';
import { runInAction } from 'mobx';
import {
updateFile,
deleteFile,
} from '@/services/commonAPI/updateFile';
import { helper, checkType } from '@/utils/T';
import Prompt from '@/utils/prompt';
import Viewer from 'react-viewer';
import patrolDataStore from '@/pages/PatrolEnter/model/patrolDataStore';
const { DCIM_DownloadZip, getFileName } = helper;
const DoUpload = (props) => {
const { item, value, onChange, handSave, isErrorUpload, ...rest } = props;
const {
EnumAcceptType = '',
EnumAcceptTypeArray = [],
EnumAcceptPicType = '',
EnumAcceptPicTypeArray = [],
} = window.DCIMAPP;
const [visible, setVisible] = React.useState(false);
const [isShow, setIsShow] = React.useState('');
const { assetId, id, isDisabled } = rest;
const { saveComponentConf } = patrolDataStore;
const [previewVisible, setPreviewVisible] = useState(false);
const [previewImage, setPreviewImage] = useState('');
const [fileList, setFileList] = useState(value || []);
const [percent, setPercent] = useState(0);
const [percentShow, setPercentShow] = useState(false);
const { disabled, size, count, isOnlyPicture, ...otherProps } =
item?.['x-props'];
const [uploadLoading, setLoading] = useState(true);
const beforeUpload = (file) => {
const isLtSize = file.size / 1024 / 1024 < size;
if (!isLtSize && size) {
Prompt.error(
window.intl.formatMessage({
id: 'DoFprmSchema.components.DoUpload.FileSize',
defaultMessage: '文件大小超出限制!',
})
);
return false;
}
if (!validFileType(file)) {
Prompt.error(
window.intl.formatMessage({
id: 'DoFprmSchema.components.DoUpload.FileFormat',
defaultMessage: '文件格式不符合上传要求!',
})
);
return false;
}
};
const validFileType = (file) => {
const fileType = isOnlyPicture
? EnumAcceptPicTypeArray
: EnumAcceptTypeArray;
const suffix = file.name.split('.')[file.name.split('.').length - 1];
const bo = fileType.includes(file.type) || fileType.includes(suffix); //
return bo;
};
const customRequest = ({
file,
onProgress,
onSuccess,
one rror,
...rest
}) => {
try {
const handleFile = (item) => {
const res = {
name: item.fileName,
uid: helper.guid(),
status: 'done',
url: `${item.url}`,
};
return res;
};
const cb = (event) => {
setPercent(((event.loaded / event.total) * 100).toFixed(2));
setLoading(false);
};
if (beforeUpload(file)) return false;
else {
// percentChange(file.size)
setPercentShow(true);
updateFile({ file }, cb).then(
(resp) => {
onSuccess(resp, file);
const _file = handleFile(resp.data);
const newFileList = fileList.concat(_file);
setPercentShow(false);
setPercent(0);
setFileList(newFileList);
onChange?.(newFileList);
handSave?.(newFileList);
!isErrorUpload &&
saveComponentConf?.(
{ default: newFileList },
assetId,
item.key
);
setLoading(true);
},
(error) => {
Prompt.error(
window.intl.formatMessage({
id: 'DoFprmSchema.components.DoUpload.UploadFailed',
defaultMessage: '上传失败,请重新选择文件',
})
);
setPercentShow(false);
setPercent(0);
one rror();
}
);
}
} catch (error) {
console.error(error);
}
};
const onDownloadHandle = (value) => {
let params = {
filename: value.name ?? value.url,
};
DCIM_DownloadZip(proxyDCIMAPI('/inspection/plan/download'), {
method: 'get',
params,
})
.then(
(res) =>
runInAction(() => {
if (res) {
handleExport(res);
}
}),
(res) =>
runInAction(() => {
Prompt.error(res.msg);
})
)
.catch((err) => console.error(err));
};
const handleExport = (res) => {
const iframe = document.createElement('a');
let url = window.URL.createObjectURL(new Blob([res.data]));
let fileName = '';
fileName = getFileName(fileName, res);
iframe.download = fileName;
iframe.href = url;
document.querySelector('body')?.appendChild(iframe);
iframe.click();
document.querySelector('body')?.removeChild(iframe);
};
const onPreviewPic = (value) => {
if (checkType.isPicType(value?.name ?? value?.url)) {
// setPreviewImage(value.url);
// setPreviewVisible(true);
showImg(value?.url);
} else {
Prompt.warn(
window.intl.formatMessage({
id: 'DoFprmSchema.components.DoUpload.PreviewNot',
defaultMessage: '该文件不支持预览!',
})
);
}
};
const handleCancel = () => {
setPreviewVisible(false); //todo: 暂无使用可去除
};
const onRemoveHandle = (value) => {
// if(uploadLoading)
deleteFile(value.name).then(
(resp) => {
const _fileList = fileList.filter(
(item) => item.uid != value.uid
);
setFileList(_fileList);
Prompt.success(
window.intl.formatMessage({
id: 'message.deleted.label',
defaultMessage: '删除成功',
})
);
onChange?.(_fileList);
handSave?.(_fileList);
!isErrorUpload &&
saveComponentConf?.(
{ default: _fileList },
assetId,
item.key
);
},
(error) => {
Prompt.error(error.msg);
// one rror();
}
);
};
//实现放大缩图片
const showImg = (src) => {
setIsShow(src);
setVisible(true);
helper.setDisplay('block');
};
return (
<div className="doUpload">
<Fragment>
<Viewer
visible={visible}
onClose={() => {
helper.setDisplay('none');
setVisible(false);
}}
images={[{ src: isShow, alt: '' }]}
/>
<Upload
accept={isOnlyPicture ? EnumAcceptPicType : EnumAcceptType}
listType="picture-card"
disabled={isDisabled}
// 移动端上传的没有uid填充
fileList={(fileList ?? []).map((file) => ({
...file,
uid: file.uid ?? file.url,
status: 'done',
}))}
beforeUpload={(file) => beforeUpload(file)}
customRequest={customRequest}
onPreview={(value) => onPreviewPic(value)}
onDownload={(value) => onDownloadHandle(value)}
onRemove={(value) => onRemoveHandle(value)}
showUploadList={{
showDownloadIcon: true,
showRemoveIcon: uploadLoading,
}}
>
{count && fileList.length >= count ? null : (
<div className="upload-btn">
{percentShow ? (
<Progress
className="progress-line"
percent={Number(percent)}
size="small"
showInfo={false}
status="active"
/>
) : (
<div className="ant-upload-text">
{window.intl.formatMessage({
id: 'common.upload',
defaultMessage: '上传',
})}
{count ? (
<span>
({fileList.length}/{count})
</span>
) : null}
</div>
)}
</div>
)}
</Upload>
<Modal
visible={previewVisible}
// title={previewTitle}
footer={null}
onCancel={handleCancel}
>
<img
alt="example"
style={{ width: '100%' }}
src={previewImage}
/>
</Modal>
</Fragment>
{/*language=SCSS*/}
<style jsx>{`
.doUpload {
:global(.ant-upload-list-item-name) {
display: block !important;
position: absolute;
bottom: 3px;
z-index: 99;
padding: 3px;
color: #63a7f9;
}
:global(.ant-upload-list-picture
.ant-upload-list-item-icon, .ant-upload-list-picture-card
.ant-upload-list-item-icon) {
top: 39%;
}
// height: 78px;
:global(.ant-upload-list-picture-card-container) {
height: 75px;
width: 75px;
}
:global(.ant-upload-list-picture-card
.ant-upload-list-item) {
height: 75px;
width: 75px;
font-size: 12px;
}
:global(.CM_DB-upload.CM_DB-upload-select-picture-card) {
width: 75px;
height: 75px;
}
:global(.ant-upload-list-picture
.ant-upload-list-item, .ant-upload-list-picture-card
.ant-upload-list-item) {
padding: 0;
}
:global(.doUpload.jsx-629672960
.ant-upload.ant-upload-select-picture-card) {
position: relative;
}
.fileList-length {
display: inline-block;
}
.upload-btn {
position: relative;
}
:global(.ant-progress-line) {
position: absolute;
bottom: -15px;
left: 50%;
transform: translateX(-50%);
}
}
`}</style>
</div>
);
};
export default DoUpload;
标签:const,upload,value,ant,item,带回,file,组件,上传 From: https://www.cnblogs.com/Simoon/p/17161415.html