Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML - Display image after selecting filename [duplicate]

People also ask

How do I show an image after select?

We have to display image after selecting file in input(type='file') using JavaScript. We can preview input file(image) with following 'readURL' user defined JavaScript function. The Preview action executed when input 'onchange' event trigged.

How do I preview a file in HTML?

First, open the html file you are editing from the File : Open dialog, or from the Open File icon on the toolbar. Click on the toggle Browser Preview on the toolbar or from the View menu. This will give you a quick browser preview. Click on the button again and it will return to the code view.


Here You Go:

HTML

<!DOCTYPE html>
<html>
  <head>
    <link
      class="jsbin"
      href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css"
      rel="stylesheet"
      type="text/css"
    />
    <script
      class="jsbin"
      src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
    ></script>
    <script
      class="jsbin"
      src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"
    ></script>
    <meta charset="utf-8" />
    <title>JS Bin</title>
    <!--[if IE]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <style>
      article,
      aside,
      figure,
      footer,
      header,
      hgroup,
      menu,
      nav,
      section {
        display: block;
      }
    </style>
  </head>
  <body>
    <input type="file" onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
  </body>
</html>

Script:

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

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

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

Live Demo


You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/


This can be done using HTML5, but will only work in browsers that support it. Here's an example.

Bear in mind you'll need an alternative method for browsers that don't support this. I've had a lot of success with this plugin, which takes a lot of the work out of your hands.