Home > Software design >  how to accept only apk file in react js?
how to accept only apk file in react js?

Time:12-08

import React from "react";
export default function DropDown() {
  const changeHandler=()=>{
    let value=document.getElementById('someId');
    let ext = value.match(/\.([^\.] )$/)[1];
    switch (ext) {
      case 'apk':
        alert('Allowed');
        break;
      default:
        alert('Not allowed');
        value = '';
    }
  };
return (
    <>
     <input type="file" id="someId" accept=".apk" onChange={changeHandler} />
    </>
  );
}

after selecting file it throws error value.match is not a function. how to resolve that if we click upload button if we upload apk file popup throws allow or else popup is not allowed

CodePudding user response:

The accept=".apk" prop in the first place if it is supported by the browser would not allow non .apk files.

If you really want to get the actual filename with the extension, the event handler itself passes an event object. You just need to access the target of that event in your change handler.

const changeHandler=(e)=>{
  const filename = e.target.files[0].name; // filename.apk
  // do whatever you want.
}

you may also use e.target.files[0].type will also show what filename type was chosen.

  • Related