Show image and upload an input

Asked

Viewed 2,231 times

5

Hi, I would like to know how to get the path of an image contained in the value of a file type input. I am using the following code:

$(document).on("change",'#Upload',function(){
         var valor=$(this).attr('value');
         var ext= (valor.substring(valor.lastIndexOf("."))).toLowerCase();
     if (ext==".jpg" || ext==".jpeg"){         
         $("#Image").attr("src", valor);
     }else{alert('Extensao "'+ext+'" nao permitida!');}
});

It returns a fakepath, ie a false path. someone could help me?

  • Barter var valor=$(this).attr('value'); for var valor=$(this).val(); does not solve the problem?

  • It also returns the following value: C:/fakepath/imagem_teste.jpg

  • I believe browsers do not allow you access to the original directory due to user security issues.

  • Some way to make a kind of image visualization to be loaded on the page itself?

  • It’s a localhost page?

2 answers

5


It doesn’t work that way. What you have access to is the contents of the file, not its path.

To show an image that corresponds to the file do so:

$(document).on("change", "#Upload", function(e) {
    showThumbnail(this.files);
});

function showThumbnail(files) {
    if (files && files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#thumbnail').attr('src', e.target.result);
        }

        reader.readAsDataURL(files[0]);
    }
}

Example running on jsfiddle

0

"fakepath" is a security measure that some browsers implement to prevent javascript from knowing the path of files.

I do not believe that there is a way to get the path without resorting to some kind of external component (flash?), or without disabling some browser security configuration.

Browser other questions tagged

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