How to grab a file extension?

Asked

Viewed 2,660 times

2

I am using JSP and HTML and need to select a file and know its extension.

The only way I know how to open a file is with input file but with it I can’t get the extension.

How can I get this result?

  • Directory or extension? On client or server?

  • 1

    I will use the file, but for this I need to know which is the extension...

2 answers

3


Using jQuery. I believe you want to get this before you send some information to the server so I did this example.

<input type="file" name="arquivo" id="arquivo" />
<div id="DivExtensao"></div>
<script>
    //Função será executada quando a página estiver totalmente carregada 
    $(document).ready(function(e) {
        //Vincular um evento no input type="file" de name = "arquivo"
        //Evento responsável por qualquer mudança no conteudo do input file
        $("#arquivo").change(function(e) {
           //pegando valor do input file
           var value = $(this).val();
           //comando split responsável na criação de um array de string 
           var values = value.split('.'); 
           if (values.length > 0){
               //pega o ultimo elemento do array que é a extensão
               $("#DivExtensao").html(values[values.length - 1]);
           } else {
               $("#DivExtensao").empty();
           }
        });     
    });     
</script>

References:

  • sorry my ignorance, but you could comment on the lines... I didn’t quite understand how your code works

  • 1

    @user7569, I made a brief description under the items I found most pertinent, and put an item Referencias that you can read to enlighten you better ... I hope I’ve helped

  • 1

    thank you very much... helped a lot!

1

In the code snippet below, you get the file extension in a simpler way:

 extensao =($("#arquivo").substring(arquivo.lastIndexOf("."))).toLowerCase();

I use this code to validate the allowed extensions for my system with the function below:

function verificaExtensaoArquivo(arquivo) { 
       extensoes_permitidas = new Array(".pdf", ".png", ".tif", ".tiff", ".bmp", ".jpeg", ".jpg"); 
       extensao = (arquivo.substring(arquivo.lastIndexOf("."))).toLowerCase();
       permite = false;   
          $(extensoes_permitidas).each(function(i){
             if (extensoes_permitidas[i] == extensao) {
                permite = true; 
                return false; 
             } 

          });
        if(!permite){
            alert("EXTENSÃO DO ARQUIVO NÃO PERMITIDA!");
            return false;  
        } 
      return true;      
   } 

Browser other questions tagged

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