我想限制上传的文件数量为10个,并且如果数量超过10个,仅显示一次错误消息。但如果我尝试一次上传 11 个文件,我的屏幕上会出现 11 次错误消息。
const beforeUpload = (file,fileList) => {
const maxFileSize = 250 * 1024 * 1024; // 250MB limit
const maxLimit = 10
if (fileList.length>maxLimit){
message.error(`Only 10 files allowed`);
return false;
}
if (file.size > maxFileSize) {
message.error(`${file.name} file upload failed (exceeds 250MB)`);
console.error("File size exceeds the limit of 250MB");
return false;
}
return true;
};
我尝试在 beforeUpload 中处理它,但如果文件超过 10 个,我可以禁用文件上传。但是我无法一次显示该消息。如果我尝试上传 11 个文件,它会显示 11 次。关于如何显示一次消息并限制文件上传有什么想法吗?
<Upload.Dragger multiple beforeUpload={beforeUpload} customRequest={handleFileUpload} showUploadlist={false}>...</Upload.Dragger>
限制一次可以上传的文件数量的最简单方法是使用 max count 属性,但在这种情况下,您不会通知用户。
如果您需要通知用户,您可以使用 ref 来控制您是否已经通知用户此错误:
const notificated = useRef(false)
function beforeUpload(file){
const index = fileList.indexOf(file);
const maxLimit = 10
if (fileList.length > maxLimit){
if (!notificated.current) {
notificated.current = true;
message.error(`Only 10 files allowed`);
}
if (index === fileList.lenght - 1) {
// reached last upload item
// we must reset notification status now
notificated.current = false;
}
return false;
}
const maxFileSize = 250 * 1024 * 1024; // 250MB limit
if (file.size > maxFileSize) {
message.error(`${file.name} file upload failed (exceeds 250MB)`);
console.error("File size exceeds the limit of 250MB");
return false;
}
return true;
};