1、文件上传(导入)-----方式一(原生html)
<button type="primary" className={styles.firmUploadBtn}>
导入
<input
type="file"
name="file"
className={styles.fileUpload}
accept=".xlsx, .xls"
onChange={(e) => {
uploadSource(e);
}}
/>
</button>
firm-upload-btn {
position: relative;
background: #ffd145;
border: 1px solid #ffd145;
border-radius: 2px;
color: #000;
font-size: 14px;
text-align: center;
margin-right: 8px;
width: 78px;
padding: 0 16px;
height: 32px;
line-height: 32px;
.file-upload {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 0;
}
}
// 导入
const uploadSource = (e) => {
if (e.target.files[0]?.size > 500 * 1024 * 1024) {
message.warning('上传文件最大不能超过500M!');
} else {
let formData = new FormData();
formData.append('file', e.target.files[0]);
uploadCheckInfoApi(formData).then((res) => {
if (res.success) {
initSearch();
message.success('导入成功!');
} else {
// message.error('导入失败!');
}
});
}
e.target.value = '';
};
---------------------------------------------------------------------------------------------------------------------------------
1、文件上传(导入)-----方式二,使用ant-d组件Upload
<Upload
name="file"
fileList={fileList}
onChange={uplodaTemplate}
beforeUpload={beforeUpload}
onPreview={handlePreview}
>
<p className="upload-template">导入文件</p>
/Upload>
const page = () => {
const [fileList, setFileList] = useState([]); // 文件上传列表
// 上传之前
const beforeUpload = (file) => {
setFileList([...fileList, file]);
FileListRef.current = [...fileList, file]; // 保存一份 可能在删除(uid)时会用到
return true;
};
// 文件查看——即下载文件
const handlePreview = (file: any) => {
// 下载
download(file, file.name);
};
// 导入文件数据
const uplodaTemplate = (info: any) => {
if (info.file.status !== 'uploading') {
const formData = new FormData();
formData.append('name', apiName);
formData.append('file', info.fileList[0]);
uploadTemplate(formData).then((res) => {
if (res.success) {
message.success('文件导入成功!');
getList(); // 上传了后更新列表
} else {
message.success(res?.mesg || '文件上传失败!');
}
});
}
}
}
2、图片上传------使用ant-d组件Upload
<div className="common-upload-img">
<Upload
// action='/FAKE_IMAGEURL'
listType="picture-card"
fileList={imageUrl}
beforeUpload={beforeImageUpload}
onPreview={handlePreview}
onRemove={handleRemove}
accept="image/png,image/jpeg,image/jpg"
onChange={handleChange}
>
{imageUrl.length >= maxCount ? null : uploadButton}
</Upload>
<Modal
visible={previewOpen}
title={previewTitle}
customText="关闭"
handleModal={handleCancel}
onCancel={handleCancel}
>
<img alt="example" style={{ width: '100%', height: 500 }} src={previewImage} />
</Modal>
</div>
function UploadImg(props: Props) {
const { name, form, type, fileList, onChange, maxCount, rules } = props;
const [imageUrl, setImageUrl] = useState([]);
const [previewImage, setPreviewImage] = useState('');
const [previewTitle, setPreviewTitle] = useState('');
const [previewOpen, setPreviewOpen] = useState(false);
const [imageUrlList, setImageUrlList] = useState([]); // 图片上传url列表
const [loading, setLoading] = useState(false);
useEffect(() => {
if (fileList && fileList.length > 0 && fileList[0]?.url) {
const urlList = fileList.map((item) => item.url);
setImageUrlList(fileList);
form?.setFieldsValue({ [name]: fileList });
setImageUrl(fileList);
} else {
form?.setFieldsValue({ [name]: [] });
setImageUrl([]);
setImageUrlList([]);
}
}, []);
// 上传按钮
const uploadButton = (
<div className="upload-icon">
{loading ? <Icon type="loading" /> : <Icon type="plus" />}
<div style={{ textAlign: 'center', color: 'rgba(255, 255, 255, 0.45)' }}>上传图片</div>
</div>
);
/**
* 图片切换
* @param info
* @returns
*/
const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
const promiseImageArray = [];
setImageUrl(newFileList);
};
// 转化为文件格式
const getBase64View = (file: RcFile): Promise<string> =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result as string);
reader.onerror = (error) => reject(error);
});
// 查看
const handlePreview = async (file: UploadFile) => {
console.info(file);
if (!file.url && !file.preview) {
file.preview = await getBase64View(file.originFileObj);
}
setPreviewImage(file.url || (file.preview as string));
setPreviewOpen(true);
setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
};
// 删除
const handleRemove = (file) =>
new Promise((resolve, reject) => {
Modal.confirm({
title: '确认删除选中的图片?',
okText: '确认',
cancelText: '取消',
onOk: () => {
let data = [];
if (file.url) {
data = imageUrlList.filter((item) => item.url !== file.url);
setImageUrlList(data);
onChange(
name,
data.map((item) => item.url),
);
} else {
data = imageUrlList.filter((item) => item.uid !== file.uid);
setImageUrlList(data);
onChange(
name,
data.map((item) => item.url),
);
}
form?.setFieldsValue({ [name]: data });
resolve(true);
},
onCancel: () => {
resolve(false);
},
});
});
// 上传图片前的钩子函数
const beforeImageUpload = (file) => {
if (!file.type.includes('image')) {
message.warning('请上传图片');
return false;
}
let uploadState = false;
setLoading(true);
console.info('图片上传。。。');
const fd = new FormData();
fd.append('file', file);
fd.append('fileType', type);
imageUploadApi(fd)
.then((res) => {
setLoading(false);
console.info(res, res.data);
if (res.success) {
const urlSource = imageUrlList.map((item) => item.url);
form?.setFieldsValue({ [name]: [...urlSource, res?.data?.filePath] });
setImageUrlList([
...imageUrlList,
{
uid: file.uid,
url: res?.data?.filePath,
},
]);
onChange(name, [...urlSource, res?.data?.filePath]);
uploadState = true;
} else {
message.error(res?.mesg || '图片上传失败!');
uploadState = false;
}
})
.catch((err) => {
setLoading(false);
console.info(err);
});
return uploadState;
};
// 关闭查看
const handleCancel = () => setPreviewOpen(false);
}