0

I am making an upload form. Here is the jquery function:

 $("#dropbrows").click(function(){
  $("#browse").trigger("click");
      $("#browse").change(function (){

  var test = $("#browse").val();

  $("#userpic").append("<a>'"+test+"'</a><img src='"+test+"' width='30' height='30' />");


});
   });

and the HTML

        <ul id="userpic" class="userpic">

            <!-- The file uploads will be shown here -->
        </ul>

As you see what am I trying to do is to make a small thumbnail upon picture select, the pic stored in 'C:\fakepath\1518290_611410375580021_371786666_n.jpg' the browser shows the full path of the pic as 'C:\fakepath\1518290_611410375580021_371786666_n.jpg' but instead of the thumbnail it shows a question mark. cause it is not able to find the physical pic file in the path, I guess.

The question is, how to let the thumbnail show the pic? What am I doing wrong here?

Thanks a lot.

Kissa Mia
  • 287
  • 7
  • 22

2 Answers2

3

Try this,

$(function(){
    $("#browse").change(function () {
       var files = this.files;
       var reader = new FileReader();
       var name=this.value;
       reader.onload = function (e) {
          $("#userpic").append("<a>'"+name+"'</a><img src='"+e.target.result+"' width='30' height='30' />");
       };
       reader.readAsDataURL(files[0]);
    });
});

Also if you are using userpic as ul then append li in your string like,

$("#userpic").append("<li>anchor and image here</li>");

Live Demo

Rohan Kumar
  • 38,998
  • 11
  • 69
  • 99
  • Rohan thanks a lot, your code shows the thumbnail but, instead of the filename i get 'data:image/jpeg;base64,/9j/4AAQS.... ' when I change test to e.target.result or get "Object when I change to "reader" how to show the file name too ? I am hiding the – Kissa Mia Jan 29 '14 at 04:42
  • I don't see any `object` in my `demo`, It just shows the `name` of image. – Rohan Kumar Jan 29 '14 at 04:55
  • now it shows the fake path again just like in my code, I tried to split 'C:\fakepath\ but that seems to be an error to separate 'C:\fakepath\ using .split() – Kissa Mia Jan 29 '14 at 05:14
  • Which browser you are using? I tested in `Firefox v 26`. – Rohan Kumar Jan 29 '14 at 05:20
1

to create an image preview of an uploaded file please check the answers in the link below:

Preview an image before it is uploaded

this is the accepted answer of that link:

Please take a look at the sample JS code below:

function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

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

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

$("#imgInp").change(function(){
    readURL(this);
});

and the associated HTML:

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

DEMO of the above code

Community
  • 1
  • 1
Jo E.
  • 6,278
  • 11
  • 44
  • 79