Need to understand, new FormData() -- When uploading, convert the content into a file stream
new FileReader()--base64 compression, currently unknown
1. Excel file export
Three kinds of export: one is purely front-end export; two kinds of back-end export: divided into back-end for address export, and export in the form of file stream, preferably back-end export, will not be stuck, the amount of data exported by the front-end is one very big
Blod : blob is a container for storing binary large objects, including large objects; create a bold object
The backend returns a stream of binary data, generating Excel:
① Click Template Acquisition--Export, pop-up box to confirm, click Confirm
② Call the interface, get the result, the responseType of the interface: 'blob'
③ Call the url method of window, create a tag, click a = url, set and click download
-- When exporting the file as pdf, modify the type: 'application/pdf;chartset=UTF-8'
// 模板获取
const getTemplate = async () => {
const res = await getStuTemplate()
// const blob = new Blob(['\ufeff' + res], { type: 'application/vnd.ms-excel' })
// 调用window的url方法
const url = window.URL.createObjectURL(res)
// 通过创建a标签实现
const link = document.createElement('a')
link.href = url
// 命名
// link.download = res?.headers['content-disposition'].split(';')[1].split('=')[1] || '模板'
link.download = decodeURI('考生信息')
document.body.appendChild(link)
// 下载文件
link.click()
// 释放内存
document.body.removeChild(link)
}
// 考生信息--导出excel模板
export async function getStuTemplate(params?: any) {
return request(`/${Proxy_Api}/entrantManage/exportExcel`, {
method: 'GET',
responseType: 'blob',
params,
})
}
// 导出 -- PDF
const getTemplate = async () => {
const res = await getStuTemplate({ code })
// 创建blob对象,解析流数据
const blob = new Blob([res], { type: 'application/pdf;chartset=UTF-8'})
// 调用window的url方法,根据解析后的blob对象创建URL 对象
const url = window.URL.createObjectURL(blob)
// 通过创建a标签实现
const link = document.createElement('a')
link.href = url
// 命名
// link.download = res?.headers['content-disposition'].split(';')[1].split('=')[1] || '模板'
link.download = decodeURI('请假统计')
document.body.appendChild(link)
// 下载文件
link.click()
// 释放内存
document.body.removeChild(link)
}
Two, excel file import - upload
①Use the Dragger component to upload, click upload and select the file
② Set the props of the component, intercept the file with the beforeUpload hook function, do not set the action address, and cancel the automatic upload
③ Through beforeUpload, intercept the default upload, process the uploaded file, and judge the file format
④ After clicking the confirmation in the modal pop-up box, create a new FormData(), use append, send a fetch request, and the returned data needs to be converted into json format
① 设置组件
<Modal destroyOnClose={true} title="数据导入" visible={isUploadOpen} onOk={handleOkUpload} onCancel={handleCancelUpload} width={550}>
<Dragger {...props} style={
{ marginBottom: 20, marginTop: 20 }}>
<p className="ant-upload-drag-icon"><InboxOutlined /></p>
<p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
<p className="ant-upload-hint">当前仅支持扩展名:.xls/.xlsx</p>
</Dragger>
<p style={
{ fontSize: 12, color: '#00000073', marginTop: 10 }}>注:若在此之前已经上传过数据而此次上传存在覆盖操作,则相关分组信息需要重新导入</p>
</Modal>
// dragger组件
② 设置组件props
// 设置文件变量
const [oneFile, setOneFile] = useState<any>();
const props: UploadProps = {
maxCount: 1, //最大数量
multiple: false, //是否支持多选
onRemove: (file) => { //删除
setOneFile(null)
},
// beforeUpload 拦截默认上传,回调参数就是file文件
// 可以对文件类型进行判断
beforeUpload: (file) => {
const fileName = file.name.substring(file.name.lastIndexOf('.') + 1, file.name.length)
const fileType = fileName == 'xls' || fileName == 'xlsx'
if (!fileType) {
message.error('上传失败,请上传xls/xlsx格式的文件')
} else {
setOneFile(file)
}
return false;
},
};
③ 上传文件
/**点击上传 */
const handleOkUpload = () => {
const formData = new FormData();
formData.append('file', oneFile as RcFile);
fetch(`${Proxy_Api}/entrantManage/importExcel/${code}`, {
method: 'POST',
body: formData,
})
.then((res) => {
return res.json()
})
.then((res) => {
if (res?.success) {
message.success('导入成功');
setOneFile(null)
setIsUploadOpen(false)
} else {
message.error(res.desc)
}
})
.catch(() => {
message.error('导入失败');
})
};
3. Upload photos
① Upload props, do not set action, set beforeUpload, intercept uploading files
② Judging the uploaded file, format, size, before each upload, modify the variable oneFile for final submission
③ Set the onChange of props. When changing the uploaded file, call the base64 method and modify the imageUrl variable to display the currently uploaded image on the page.
④ Submit, new FormData to convert to file stream, use append, send fetch request, return data needs to be converted into json format
① 设置组件
const [imageUrl, setImageUrl] = useState<any>();
<Form.Item label="考点图片" name="photo">
<Upload {...props} >
{imageUrl ?
// 上传图片后,图片反显,图片+上传按钮
[<img src={imageUrl} alt="avatar" style={
{ height: '60px', marginRight: 10 }} />, <Button icon={<UploadOutlined />}>上传文件</Button>]
: <Button icon={<UploadOutlined />}>上传文件</Button>}</Upload>
</Form.Item>
② 设置上传props
// 上传的props
const props: UploadProps = {
maxCount: 1,
multiple: false,
name: "avatar",
action: "#",
listType: "picture",
className: "avatar-uploader",
showUploadList: false,
onRemove: (file) => {
setOneFile(null)
},
/**上传文件之前的钩子,参数为上传的文件,可设置文件格式和大小,若返回false停止上传 */
beforeUpload: beforeUpload,
onChange: handleChange,
};
③ 提交上传文件
const [oneFile, setOneFile] = useState<any>(); //文件变量
/**上传文件之前的钩子,参数为上传的文件,可设置文件格式和大小,若返回false停止上传 */
const beforeUpload = (file: RcFile) => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('请上传 JPG/PNG 格式的图片!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('图片需要小于 2MB!');
}
setOneFile(file)
return isJpgOrPng && isLt2M;
// 返回false ,不请求,但是获取不到显示图片,用action:"#",替换不请求
// return false;
};
④ base64设置反显图片
// 上传判断,是否显示图片
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result as string));
// 方法可以将读取到的文件编码成DataURL ,可以将资料(例如图片、excel文件)内嵌在网页之中,不用放到外部文件
reader.readAsDataURL(img);
};
⑤ onChange--上传文件改变时的回调 */
const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
if (info.file.status === 'uploading') {
return;
}
if (info.file.status === 'done') {
getBase64(info.file.originFileObj as RcFile, (url) => {
setImageUrl(url);
});
}
};
⑥ 提交
/**新增、修改--确认 */
const handleOk = () => {
addForm.validateFields().then(async (values) => {
if (imageUrl) {
const { address, examYear, code, name } = values
let newForm = new FormData()
newForm.append("address", address);
newForm.append("examYear", examYear);
newForm.append('code', code);
newForm.append('name', name);
newForm.append('photo', oneFile);
fetch(`${Proxy_Api}/examPlaceManage`, {
method: 'POST',
body: newForm,
})
.then((res) => {
return res.json()
})
.then((res) => {
if (res?.success) {
message.success('新增成功');
setOneFile(null)
setIsModalOpen(false);
} else {
const { desc } = res
message.error(desc);
}
})
.catch(() => {
message.error('新增失败');
})