Home > front end >  Is there a way to restrict your input element to only accept videos?
Is there a way to restrict your input element to only accept videos?

Time:10-11

I have an input element with type set to file which I am using to upload files. The problem is it also accepts images but I don't want that. I only want videos to be accepted. Is there a way to go about it?

 <input
   type="file"
   id="file"
   ref={inputFile}
   onChange={(event) => handleVideoUpload(event.target.files[0])}
      }

CodePudding user response:

The accept attribute on the input should do the job:

https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept

CodePudding user response:

Just use accept prop

If required an extra step to validate - you can check the condition before submitting / posting by using File type - MIME of video

a sample e.g.

const { useRef } = React;

const App = () => {
  const fileRef = useRef(null);
  
  const handleVideoUpload = (file) => {
    if(!file.type.includes("video")){
      alert("not a video and don't submit, just return")
      return
    }else{
      alert("It's a video ... proceed submitting")
    }
  }

  return (
    <div>
      <input
        type="file"
        id="file"
        accept="video/*"
        ref={fileRef}
        onChange={(event) => handleVideoUpload(event.target.files[0])}
      />
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

  • Related