Allow Select PDF only in JS

Asked

Viewed 883 times

2

I wonder how to do that when choosing the file to upload it filter by extension . html native pdf or by JS, Jquery.

Using type="file" it brings all the files.

<!DOCTYPE html>
<html>
<body>

<h1>Selecione o arquivo PDF:</h1>

<h3>Selecione o PDF:</h3>
<form action="/action_page.php">
  <input type="file" name="myFile"><br><br>
  
</form>



</body>
</html>

3 answers

5


You can use it this way:

<input type="file" accept="application/pdf">

Here has a list of file types and code mime that you can use, if you want to use more than one, you can separate with |

Ex.:

<input type="file" accept="application/pdf|image/*">


MDN Compatibility List

2

You can use valid Javascript for any browser for this.

<html>
<body>
    <h1>Selecione o arquivo PDF:</h1>
    <h3>Selecione o PDF:</h3>
    <form action="/action_page.php">
        <input type="file" name="myFile"><br><br>
    </form>

<script>
    var file = document.getElementsByTagName('input').value();
    var tipo = file.split('.').pop();

    if(tipo != 'pdf'){
        alert('Arquivo não suportado');
    }
</script>
</body>
</html>

1

In full, we have the following answer to your case:

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>Selecione o arquivo PDF:</h1>
    
    <h3>Selecione o PDF:</h3>
    <form action="/action_page.php">
      <input type="file" accept="application/pdf">
      <br><br>
      
    </form>
    
    </body>
    </html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.