【发布时间】:2021-04-10 03:38:10
【问题描述】:
我在我的应用程序中使用了来自 Ant Design 的上传器。
function beforeUpload(file) {
const filesFormats = [".doc", ".docx", "application/pdf"];
console.log(file);
const isRightFormat = filesFormats.includes(file.type);
console.log(isRightFormat);
if (!isRightFormat) {
message.error("You can only upload pdf and doc files");
return;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error("Image must smaller than 2MB!");
}
return isRightFormat && isLt2M;
}
class Avatar extends React.Component {
state = {
loading: false
};
handleChange = (info) => {
console.log("info, ", info);
if (info.file.status === "uploading") {
this.setState({ loading: true });
return;
}
if (info.file.status === "done") {
// Get this url from response in real world.
this.setState({ loading: false });
}
};
render() {
const { loading } = this.state;
const uploadButton = (
<div>
{loading ? <LoadingOutlined /> : <PlusOutlined />}
<div style={{ marginTop: 8 }}>Upload</div>
</div>
);
return (
<Upload
name="avatar"
listType="picture-card"
className="avatar-uploader"
showUploadList={true}
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
beforeUpload={beforeUpload}
onChange={this.handleChange}
>
{uploadButton}
</Upload>
);
}
}
我想要做的是限制某些可以上传的文件格式。比如我的限制不能上传图片:
const filesFormats = [".doc", ".docx", "application/pdf"];
console.log(file);
const isRightFormat = filesFormats.includes(file.type);
console.log(isRightFormat);
if (!isRightFormat) {
message.error("You can only upload pdf and doc files");
return;
}
代码有效,但是当我上传图片时,它仍然作为列表项出现在上传器图标中,但这应该是不可能的,因为我设置了限制。
为什么会发生以及如何实现我上面描述的?
【问题讨论】: