Show image and upload an input

5

Hello, I would like to know how to get the path of an image contained in the value of an input of type file. I'm 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. could anyone help me?

    
asked by anonymous 07.04.2014 / 18:08

2 answers

5

It does not work that way. What you have access to is the contents of the file, not the path of it.

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

    
07.04.2014 / 18:27
0

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

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

    
07.04.2014 / 18:28