I'm using JSP and HTML and I need to select a file and know its extension.
The only way I can open a file is with input file
but with it I can not get the extension.
How can I get this result?
I'm using JSP and HTML and I need to select a file and know its extension.
The only way I can open a file is with input file
but with it I can not get the extension.
How can I get this result?
Using jQuery . I believe you want to get this before sending some info to the server so I made 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:
In the code snippet below, you'll get the file extension simpler:
extensao =($("#arquivo").substring(arquivo.lastIndexOf("."))).toLowerCase();
I use this code to validate the extensions allowed 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;
}