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
Add a ment  | 

3 Answers 3

Reset to default 5

You 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>

本文标签: htmlhow to validation the input (typequotfilequot) by javascript for upload images onlyStack Overflow