0

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

1
  • Remove the uploaded file? You'll need server side code for that Commented May 27, 2018 at 15:12

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

4 Comments

What will happen when i rename an exe into .jpg and upload?
@Cerlin The file will be uploaded, but since it's not an image, nothing will display and since it's an .exe but with the wrong file extension, it wouldn't execute either. Chances are that the server would detect the code base as executable and block it in the first place.
Wouldn't it be safer to check mime type compared to the solution provided here?
@Cerlin I'm not entirely sure. Since the input type=file only is responsible for selecting a file (and not uploading it), I don't know that you can check the mime type at that point.
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.