第一种情况:仅支持单个文件上传,允许格式为excel文件
import { InboxOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import React from 'react';
const { Dragger } = Upload;
const App = (prop) => {
const [fileList, setFileList] = useState([]);
const props = {
name: 'file',
beforeUpload(file, fileList) {
const isJpgOrPng = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';
if (!isJpgOrPng) {
message.error('您只能上传XLSX/XLS文件!');
setFileList([]);
} else {
setFileList(fileList);
}
return false; // 阻止默认上传事件(原上传默认会请求一个url,就算什么都不写也会请求)
},
onRemove() {
setFileList([]);
}
};
return (
<Dragger {...props} fileList={fileList}>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text">Click or drag file to this area to upload</p>
<p className="ant-upload-hint">
Support for a single or bulk upload. Strictly prohibit from uploading company data or other
band files
</p>
</Dragger>
)
};
export default App;
第二种情况:支持多文件上传,上传文件做类型限制,且限制文件大小
import { InboxOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import React from 'react';
const { Dragger } = Upload;
const App = (prop) => {
const [fileList, setFileList] = useState([]);
const props = {
name: 'file',
multiple: true,
beforeUpload(file) {
return new Promise((resolve, reject) => {
const validTypes = ['image/jpeg', 'image/png', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
const isValidType = validTypes.includes(file.type);
if (!isValidType) {
message.error('只能上传 PDF、Word 文档或图片文件!');
return false; // 阻止文件被添加到fileList
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('文件大小不能超过 10MB!');
return false; // 阻止文件被添加到fileList
}
reject(true); // 阻止默认上传事件(原上传默认会请求一个url,就算什么都不写也会请求)
});
},
onChange(info) {
const { file, fileList } = info;
if (file.status === 'done') {
message.success(`${file.name} 文件上传成功.`);
} else if (file.status === 'error') {
message.error(`${file.name} 文件上传失败.`);
}
setFileList(fileList);
},
onRemove(file) {
const index = fileList.indexOf(file);
const newFileList = fileList.slice();
newFileList.splice(index, 1);
setFileList(newFileList);
},
};
return (
<Dragger {...props} fileList={fileList}>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text">Click or drag file to this area to upload</p>
<p className="ant-upload-hint">
Support for a single or bulk upload. Strictly prohibit from uploading company data or other
band files
</p>
</Dragger>
)
};
export default App;