如何通过javascript验证输入(类型="文件")仅用于上传图像?

时间:2018-05-27 15:10:49

标签: javascript html file-upload upload image-uploading

我需要输入仅上传图像, 我试图使用此代码, 但如果我从上传窗口中选择所有文件,我仍然可以使用一些.exe文件, 它只是提醒,我可以按确定,然后文件仍然上传,我可以按提交。

  

如何删除上传的文件??



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()">
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

除了警告用户之外,您还需要重置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()">

答案 1 :(得分:1)

您应该阅读this MDN article,以便更好地处理来自input[type=file]

的文件

回答你的问题,你仍然可以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)">

答案 2 :(得分:0)

这是上面使用 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>