admin 管理员组文章数量: 1086019
i need the input uploading the images only, i'am tried to use this code, but i still can some .exe files if i select all files from upload window, its just give alert and i can press ok then the file still uploaded and i can press submit.
how to remove the uploaded file??
function validateFileType(){
var fileName = document.getElementById("fileName").value,
idxDot = fileName.lastIndexOf(".") + 1,
extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//TO DO
}else{
alert("Only jpg/jpeg and png files are allowed!");
}
}
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()">
i need the input uploading the images only, i'am tried to use this code, but i still can some .exe files if i select all files from upload window, its just give alert and i can press ok then the file still uploaded and i can press submit.
how to remove the uploaded file??
function validateFileType(){
var fileName = document.getElementById("fileName").value,
idxDot = fileName.lastIndexOf(".") + 1,
extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//TO DO
}else{
alert("Only jpg/jpeg and png files are allowed!");
}
}
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()">
Share
Improve this question
asked May 27, 2018 at 15:10
Abdallah El-RashedyAbdallah El-Rashedy
8713 gold badges11 silver badges21 bronze badges
1
- Remove the uploaded file? You'll need server side code for that – Luca Kiebel Commented May 27, 2018 at 15:12
3 Answers
Reset to default 5You need to reset the input
in addition to alerting the user:
let file = document.getElementById("fileName");
function validateFileType(){
var fileName = file.value,
idxDot = fileName.lastIndexOf(".") + 1,
extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//TO DO
}else{
alert("Only jpg/jpeg and png files are allowed!");
file.value = ""; // Reset the input so no files are uploaded
}
}
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()">
You should probably read this MDN article to get better experience with handling files from input[type=file]
Answering your question, you still can input.value = ""
function validateFileType(input){
var fileName = input.value,
idxDot = fileName.lastIndexOf(".") + 1,
extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
if (["jpg", "jpeg", "png"].includes(extFile)){
//TO DO
} else {
alert("Only jpg/jpeg and png files are allowed!");
input.value = ""
}
}
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType(this)">
Here is a similar solution from above using React.
const {useState, useRef, useEffect} = React;
const FileUploader = () => {
const [currentImage, setImage] = useState(null);
const [hasError, updateErrorState] = useState(false);
const imageInputRef = useRef();
const handleInvalidFileUpload = () => {
return (
<div className="file-uploader__file-upload-error">
Invalid file upload. Please upload image files only.
</div>
);
};
const handleImageFileChange = e => {
// reset error state
updateErrorState(false);
const fileName = e.target.value;
const fileTypeDotIndexPosition = fileName.lastIndexOf(".") + 1;
const slicedFileTypeFromFilePath = fileName.slice(fileTypeDotIndexPosition);
// image validation regex
const hasImageFile = /(image\/(png|jpg|jpeg))/gi;
// prettier-ignore
if (!hasImageFile.test(e.target.files[0].type) && !hasImageFile.test(slicedFileTypeFromFilePath)) {
return updateErrorState(true);
}
console.log(e.target.files[0].type);
// set image state with uploaded image file
setImage(e.target.files[0]);
};
const handleRemoveImage = e => {
imageInputRef.current.value = "";
setImage(null);
};
return (
<div className="file-uploader__container">
<label className="file-uploader__upload-image-button">
Upload Image
<input
id="fileUploaderInput"
style={{ display: "none" }}
type="file"
accept="image/png, image/jpeg, image/jpg"
onChange={handleImageFileChange}
ref={imageInputRef}
/>
</label>
{hasError ? handleInvalidFileUpload() : ""}
<button
className="file-uploader__remove-image-button"
disabled={!currentImage ? true : false}
onClick={handleRemoveImage}
>
Remove Image
</button>
</div>
);
};
ReactDOM.render(
<FileUploader/>,
document.getElementById("root")
);
h1,
p {
font-family: Lato;
}
.file-uploader__upload-image-button {
padding: 0.6rem 1rem;
border: 1px solid gray;
border-radius: 5px;
cursor: pointer;
grid-row: 1;
}
.file-uploader__remove-image-button {
padding: 0.6rem 1rem;
border: 1px solid gray;
border-radius: 5px;
cursor: pointer;
grid-row: 2;
}
.file-uploader__analyze-image-button {
padding: 0.6rem 1rem;
border: 1px solid gray;
border-radius: 5px;
cursor: pointer;
grid-row: 3;
}
.file-uploader__container {
display: grid;
grid-template-rows: 1fr 1fr 1fr;
gap: 0.6rem;
padding: 0 1rem;
justify-items: stretch;
align-items: center;
justify-content: space-between;
grid-template-columns: 1fr 1fr 1fr;
}
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
版权声明:本文标题:html - how to validation the input (type="file") by javascript for upload images only? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744088706a2531625.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论