[英]how to display "No Data Found" when user type wrong name in input field which is not in API in React
[英]Display an error message when upload wrong image type in input field using react
我正在尝试显示“请仅上传图像格式”的错误消息。 这是我返回以显示错误消息的代码,当上传 pdf 而不是上传图像时,应该显示错误消息。 我正在使用反应 typescript。任何帮助将不胜感激。
const [fileLogoError, setfileLogoError] = useState("");
const [selectedLogoFile, setselectedLogoFile] = useState<File>();
const handleLogoChange = (event: React.ChangeEvent<HTMLInputElement>) => {
event.preventDefault()
if (event.target.files[0].type == "image/*") {
setselectedLogoFile(event.target.files[0])
} else {
setfileLogoError("Please upload only Image Format");
}
}
return (
// Uploading Image
<input
id="CT_SelectFile"
onChange={handleLogoChange}
name="file"
ref={fileUpload}
hidden
multiple type="file"
accept="image/*"
/>
// Displaying the Image
{selectedLogoFile ?
<>
<img src={imageUrl} height="45px" />
<Typography variant='subtitle1>
<span>{selectedLogoFile.name}</span>
</Typography>
</>
:
<>
{fileLogoError ?
<Typography variant='subtitle1' >
{fileLogoError}
</Typography>
:
<>
<img src={previewFile} width="40px" height="40px" />
<Typography variant='subtitle1' >
Upload your Image
</Typography>
</>
}
</>
}
)
预期 Output :当仅上传图像类型时,它应该接受并显示图像以供预览,如果它不是图像类型,它应该显示错误消息。
问题在于确定是否显示图像预览或错误消息的条件。 条件event.target.files[0].type == "image/*"
检查文件类型是否恰好是image/*
但它从来不是。 假设您上传了一个png
文件,那么类型将是image/png
而不是image/*
。 不要直接检查image/*
,而是使用regexp 。
const handleLogoChange = (event: React.ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
const {files} = event.target;
if(!files) return;
if (new RegExp("image/*").test(files[0].type)) {
setselectedLogoFile(files[0]);
setfileLogoError("");
} else {
setfileLogoError("Please upload only Image Format");
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.