How to upload preview image before upload through JavaScript

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>

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


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')


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.

Tags:

Javascript