How to validate an upload by filename?

0

I'm trying to validate the upload of a file, and it should always be called new.mpg , otherwise the program will not work.

function validarNomeArquivo(){
    //variavel que recebe o nome do arquivo
    var  oImg = "bgs/newFile.mpg";
    //variavel para comparar o input 
        var x = document.getElementById('fileBgAtualHD').value;;
                if(x==oImg){
                alert("yes");
                alert(x + " x yes ");
                alert(oImg + "  oImg yes ");
                    return true;
            }
                else{
                    alert("no");
                    alert(x + "  x no");
                    alert(oImg + "  oImg no ");
                    return false;
                }
        }
    
asked by anonymous 30.11.2017 / 17:31

2 answers

0

The problem is that by appending a file, JavaScript also creates a path , so the value element looks something like this: C:\fakepath\nome-do-arquivo.jpg .

For this reason the condition will always be false in your code.

Try to leave your function like this:

function validarNomeArquivo() {
    var oImg = 'new.mpg';
    var x = document.getElementById('fileBgAtualHD').value;

    x = x.split('\');
    x = x[x.length - 1];

    if (x == oImg) {
        return true;
    } else {
        return false;
    }
}
    
30.11.2017 / 18:16
0

You can use the name property of File object .

It would be

function validaName(el) {
  var name = el.files[0].name
  if (name != 'newFile.mpg') {
    console.log('erro: O nome do arquivo é: ' + name)
  }
}
Upload: <input type="file" onchange="validaName(this)" />
    
30.11.2017 / 18:37