Create a live preview of the image (before uploading it) with jQuery

I want to create a preview image before uploading to the server using jQuery.

My code, js code:

$(function(){ Test = { UpdatePreview: function(obj){ // if IE < 10 doesn't support FileReader if(!window.FileReader){ // don't know how to proceed to assign src to image tag } else { var reader = new FileReader(); var target = null; reader.onload = function(e) { target = e.target || e.srcElement; $("img").prop("src", target.result); }; reader.readAsDataURL(obj.files[0]); } } }; }); 

My html:

  <input type='file' name='browse' onchange='Test.UpdatePreview(this)' /> <br/><br/> <img src="#" alt="test" width="128" height="128" /> 

See jsfiddle: http://jsfiddle.net/aAuMU/

After onload I see the src of the image (using the Google console application) and looks like this:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD//gAEKgD/4gv4SUNDX1BST0ZJTEUAAQEAAAvoAAAAAAIAAABtbnRyUkdCIFhZWiAH2QADABsA...

Is this a way to get image base in javascript and assign image in case i use IE as browser?

FileReader does not work in IE <10.

+5
source share
2 answers

If you need this to get a good effect, you can use flash, as in https://github.com/mailru/FileAPI

But when I needed to show the image to the user, because I needed to allow the user to select the area for torsion, then I used the form inside the hidden iframe and uploaded the image to the server and sent back the uri image data so that I could get uri data and replace image src , then, when the region was selected, I did not send the image back as a file, but as uri data. In older browsers, this means that you download the image twice, but I did not want to use flash, as in some cases the flash drive also cannot be installed there.

+1
source

Instead

 $("img").prop("src", target.result); 

records

 $("#ImageId").attr("src", target.result); 

Where ImageId is the identifier of your img tag.

-4
source

Source: https://habr.com/ru/post/953465/


All Articles