简体   繁体   English

如何通过javascript验证输入(type =“file”)仅用于上传图像?

[英]how to validation the input (type=“file”) by javascript for upload images only?

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.我只需要上传图像的输入,我尝试使用此代码,但如果我从上传窗口中选择所有文件,我仍然可以使用一些 .exe 文件,它只是发出警报,我可以按确定,然后文件仍然上传和我可以按提交。

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()">

You need to reset the input in addition to alerting the user:除了提醒用户之外,您还需要重置input

 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]您可能应该阅读这篇 MDN 文章以获得更好的处理来自input[type=file]文件的经验

Answering your question, you still can input.value = ""回答你的问题,你还是可以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.这是上面使用 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.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM