Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

javascript - Create live preview of image (before upload it) using JQuery

I want to create a preview for image before upload it on 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 image (using Google console application) and it looks like:

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

It is a way to get in javascript the base of image and assign to image in case I'm using IE as browser ?

FileReader doesn't work in IE < 10.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you need it as getting nice effect then you could use flash like they do in https://github.com/mailru/FileAPI

But when i needed to show image to user because i needed to let user select area for croping then i used form inside hidden iframe and uploaded image to server and sent back image data uri so i was able to get data uri and replace image src attribute, then when area was selected i did not send image back as file but as data uri. In old browsers it means you upload image twice, but i did not want to use flash as in some cases flash may also not be installed there.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...