react 文件上传限制格式类型大小
import React from 'react'
import { Upload, message, Button, Card } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
export default function Index() {
const beforeupload = (file, fileList) => {
const islt5M = file.size / 1024 / 1024 < 5
if (!islt5M) {
message.error('文件夹过大!!')
const index = fileList.indexOf(file)
fileList.splice(index, 1)
return false
}
const fileType = file.name
.substr(file.name.lastIndexOf("."))
.toLowerCase(); // 获取文件后缀名
if (fileType !== '.excel' && fileType !== '.xls') {
message.error('请选择正确格式文件夹')
// 如果错的话就把这个文件夹删掉
const index = fileList.indexOf(file)
fileList.splice(index, 1);
return false
}
}
const change = (fileInfo) => {
if (fileInfo.file.response === 'success') {
message.success('导入成功')
}
if (fileInfo.file.response) {
message.error(
`导入异常记录:${fileInfo.file.response}请修改`
)
}
}
return (
<div>
<Card>
<Upload
method='post'
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
onChange={change}
beforeUpload={beforeupload}
directory>
<Button icon={<UploadOutlined />}>导入</Button>
</Upload>
<span >文件格式不能超过5M,仅允许导入“execl和xls”类型文件</span>
</Card>
</div>
)
}