9

I want to preview an image before uploading it to the server. I have written a little bit code for it, but it is only being previewed in Internet Explorer, not in other browsers like Safari, Chrome, Firefox, due to some type of security reasons. Is there any solution to preview the image in these browsers?

    <body>
       <form name="Upload" enctype="multipart/form-data" method="post">
           Filename: <INPUT type="file" id="submit">
           <INPUT type="button" id="send" value="Upload">
       </form>
       <div 
           id="div" 
           align="center" 
           style="height: 200px;width: 500px;border-style: ridge;border-color: red">
       </div>
    </body>

    <script type="text/javascript">
        var img_id=0
        var image = new Array()
        document.getElementById('send').onclick=function()
        {
            img_id++
            var id="imgid"+img_id
            image = document.getElementById('submit').value;
            document.getElementById('div').innerHTML="<img id='"+id+"' src='"+image+"' width=500px height=200px>"
        }
    </script>
</html>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Zain
  • 4,605
  • 11
  • 30
  • 31

8 Answers8

19

For Firefox. Because of security it has a truncated path. However, they have provided other ways of doing this:

var img = document.createElement("IMG");
if(document.all)
    img.src = document.getElementById('submit').value;
else
    // Your solution for Firefox.
    img.src = document.getElementById('submit').files.item(0).getAsDataURL();
document.getElementById('div').appendChild(img);

The below is working in Internet Explorer 7 and Firefox 3.

<style type="text/css">
    #prevImage {
        border: 8px solid #ccc;
        width: 300px;
        height: 200px;
    }
</style>
<script type="text/javascript">
    function setImage(file) {
        if(document.all)
            document.getElementById('prevImage').src = file.value;
        else
            document.getElementById('prevImage').src = file.files.item(0).getAsDataURL();
        if(document.getElementById('prevImage').src.length > 0) 
            document.getElementById('prevImage').style.display = 'block';
    }
</script>
<pre>
     IE8 needs a security settings change: internet settings, security, custom level :

     [] Include local directory path when uploading files to a server
 ( ) Disable
 (o) Enable 
</pre>
<form>
    <input type="file" name="myImage" onchange="setImage(this);" />
</form>
<img id="prevImage" style="display:none;" />

Documentation of File List object on MDC

Ramiz Uddin
  • 4,259
  • 4
  • 35
  • 71
  • I didn't check it in Chrome. will get back to you in few minutes on this. – Ramiz Uddin Nov 04 '10 at 06:50
  • @Zain which version of Chrome you have. – Ramiz Uddin Nov 04 '10 at 07:38
  • @Zain chrome seems more secure than FF :) 'File' is supported in Chrome has size, fileName, name, etc. properties but doesn't have 'getAsDataURL()'. I've looked into other options but seems there is no such good options we have for Chrome. I'll post this on chrome dev group see what they got on this. – Ramiz Uddin Nov 04 '10 at 07:44
  • Really Thnxs a lot Ramiz.. :) – Zain Nov 04 '10 at 07:46
  • @ user648372 I've updated my post. Check the tag. There are some security settings which you have to change in order to allow it works for you. – Ramiz Uddin May 03 '11 at 09:19
  • I've got this working OK in Firefox, but I really need it to work in IE and Chrome too. Are there any other scripts I can dd to this so that it works cross-browser? – Adam Moss Sep 23 '11 at 13:13
  • It should be working in IE but I am still not sure about Chrome. – Ramiz Uddin Sep 24 '11 at 06:34
  • The result is not consistent. When I try to upload a different image, it won't show preview, but on some, it will. Weird results I guess which I honestly don't have any idea how to solve it. – PinoyStackOverflower Nov 26 '12 at 01:41
2

uploadFile(event: any) {
    const image: any = document.getElementById('output');
    image.src = URL.createObjectURL(event.target.files[0]);
}
<div>
    <img id="output" width="200" />
</div>
<div class="form-group">
    <label for="exampleFormControlFile1">File Input</label>
    <input type="file" (change)="uploadFile($event)" class="form-control-file" />
</div>
1

just have a look on following link related on file API, it works for IE9+ i checked it does not work for IE8 it shows how to preview image and text files http://www.xul.fr/en/html5/filereader.php FileReader, loading an image in a webpage

FileReader allows access to the local file system and load documents with just JavaScript code.

This completes the for selecting local file, as this tag can only provide the content of this file to a script on the server, with the form data.

Compatibility test

The current browser recognizes it the File API, which includes the FileReader object?

Result File API supported. Source code of the test:

<script>
if (window.File && window.FileReader && window.FileList && window.Blob) 
  document.write("<b>File API supported.</b>");
else
  document.write('<i>File API not supported by this browser.</i>');
</script>   

HTML code:

<input type="file" id="getimage">

<fieldset><legend>Your image here</legend>
    <div  id="imgstore"></div>
</fieldset> 

JavaScript code:

<script>
function imageHandler(e2) 
{ 
  var store = document.getElementById('imgstore');
  store.innerHTML='<img src="' + e2.target.result +'">';
}

function loadimage(e1)
{
  var filename = e1.target.files[0]; 
  var fr = new FileReader();
  fr.onload = imageHandler;  
  fr.readAsDataURL(filename); 
}

window.onload=function()
{
  var x = document.getElementById("filebrowsed");
  x.addEventListener('change', readfile, false);
  var y = document.getElementById("getimage");
  y.addEventListener('change', loadimage, false);
}
</script>
saeed
  • 2,342
  • 2
  • 18
  • 40
1

This works fine for me in FF 3.6, IE 8, Safari 4.0, and Chrome 3.195.

A few style pointers though:

  • Don't use a fixed-width preview area, your picture will be distorted to fit the area
  • Instead of document.getElementById() use this:

    function $(id) { return document.getElementById(id); }

  • Example: $('send')

Ben
  • 47,286
  • 44
  • 159
  • 208
  • Steve..Will you please explain it to me (function $(id) { return document.getElementById(id); }) ..a little bit..Shall be very thankful – Zain Nov 04 '10 at 05:16
  • @Zain He is providing a shorthand way to use `document.getElementById()`. It is verbose, so the `$()` shortcut is helpful. – alex Nov 04 '10 at 05:48
1

It's not possible to grab a user file before upload, except using the new File API:

Example: Showing thumbnails of user-selected images

This will not, of course, be cross-browser. There might also be a way to do it via Flash and data URLs (or just previewing in Flash), but I prefer to avoid JavaScript <-> Flash integration.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
theazureshadow
  • 8,053
  • 5
  • 31
  • 46
  • Thank you Pradeep and theazureshadow, however, I find it hard to believe that we cannot open an image in the browsers (FF, Webkit based). Please have a look at the web application from 'Mugtug' called Darkroom (http://mugtug.com/darkroom/). This web application lets a user load an image for further manipulation (Open icon on top left of the web application), I am wanting to achieve the same function of popping up a dialogue box upon click, so a user can select an image for display. Any thoughts? – Zain Nov 04 '10 at 06:13
  • Like I said, you can do it with html5. That's how Mugtug does it: [Mugtug Darkroom is a Browser-Based Photo Editor Powered Entirely by HTML5](http://www.petapixel.com/2010/05/20/mugtug-darkroom-is-a-browser-based-photo-editor-powered-entirely-by-html5/) – theazureshadow Nov 04 '10 at 06:25
0

if input type is file then using htmlfilereader function can we see the preview of html page? using accept type ="text/html"

i got the file description and size...

<script>
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
      output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
                  f.size, ' bytes, last modified: ',
                  f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                  '</li>');
    }
    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

above mention problem is related with offline local stored html pages. we can see the preview of live page using live url as-

<html>
    <head>
    <!--[if IE]>
    <style>
    #frame {
        zoom: 0.2;
    }
    </style>
    <![endif]-->
    <style>
    #frame {
        width: 800px;
        height: 520px;
        border: none;
        -moz-transform: scale(0.2);
        -moz-transform-origin: 0 0;
        -o-transform: scale(0.2);
        -o-transform-origin: 0 0;
        -webkit-transform: scale(0.2);
        -webkit-transform-origin: 0 0;
    }
    </style>
    </head>
    <body>
    <iframe id="frame" src="http://www.bing.com">
    </iframe>
    </body>
    </html

>

shailendra pathak
  • 612
  • 1
  • 7
  • 25
0

It's Simple just use this

In your HTML file use

<div>
<form id="form1" runat="server">
        <input type='file' id="imgInp" />
        <br>
        <img id="blah" src="http://i.imgur.com/zAyt4lX.jpg" alt="your image" height="100" />
    </form>
<div>

And inside your java script file just write this

<script>

 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);
    });
</script>
Abhijit Chakra
  • 2,849
  • 28
  • 59
-1

This works fine in FF 3.6, IE 9, Safari 4.0, and Chrome 3.195.

var reader = new FileReader();

function preview(what) {
     if(jQuery.browser.msie || jQuery.browser.safari || jQuery.browser.chrome) {
         document.getElementById("preview-photo").src=what.value;
         return;
    }
    else{                   
        // array with acceptable file types
        var accept = ["image/png","image/jpeg","image/jpg","image/gif"];

        // if we accept the first selected file type
        if (accept.indexOf(what.files[0].type) > -1) {
            if(what.files && what.files[0]){
                  reader.readAsDataURL(what.files[0]);
                  document.getElementById("preview-photo").src=reader.result;
            }
        }       
    }
}