Preview an image before it is uploaded












1288















I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.



How can I do this?










share|improve this question

























  • Note that unless you use Gears or another plugin you cannot manipulate the image inside the browser: code.google.com/p/chromium/issues/detail?id=32276

    – Steve-o
    Dec 16 '10 at 9:58











  • Check out this pure JavaScript approach, including its answer and there Ray Nicholus' comment for the final solution: stackoverflow.com/questions/16430016/…

    – Jonathan Root
    Oct 17 '13 at 15:05











  • Here's a nice detailed article with live demo codepedia.info/2015/06/…

    – Satinder singh
    Jul 27 '15 at 15:40






  • 3





    Here's a simple solution that doesn't use jquery: developer.mozilla.org/en-US/docs/Web/API/FileReader/…

    – John Gilmer
    Aug 4 '16 at 19:22











  • angulartutorial.net/2017/02/…

    – Prashobh
    Feb 16 '17 at 14:18
















1288















I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.



How can I do this?










share|improve this question

























  • Note that unless you use Gears or another plugin you cannot manipulate the image inside the browser: code.google.com/p/chromium/issues/detail?id=32276

    – Steve-o
    Dec 16 '10 at 9:58











  • Check out this pure JavaScript approach, including its answer and there Ray Nicholus' comment for the final solution: stackoverflow.com/questions/16430016/…

    – Jonathan Root
    Oct 17 '13 at 15:05











  • Here's a nice detailed article with live demo codepedia.info/2015/06/…

    – Satinder singh
    Jul 27 '15 at 15:40






  • 3





    Here's a simple solution that doesn't use jquery: developer.mozilla.org/en-US/docs/Web/API/FileReader/…

    – John Gilmer
    Aug 4 '16 at 19:22











  • angulartutorial.net/2017/02/…

    – Prashobh
    Feb 16 '17 at 14:18














1288












1288








1288


635






I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.



How can I do this?










share|improve this question
















I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.



How can I do this?







javascript jquery file-upload






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 6 '11 at 10:49









Justin

65.2k40185326




65.2k40185326










asked Dec 16 '10 at 9:51









SimbianSimbian

6,5403138




6,5403138













  • Note that unless you use Gears or another plugin you cannot manipulate the image inside the browser: code.google.com/p/chromium/issues/detail?id=32276

    – Steve-o
    Dec 16 '10 at 9:58











  • Check out this pure JavaScript approach, including its answer and there Ray Nicholus' comment for the final solution: stackoverflow.com/questions/16430016/…

    – Jonathan Root
    Oct 17 '13 at 15:05











  • Here's a nice detailed article with live demo codepedia.info/2015/06/…

    – Satinder singh
    Jul 27 '15 at 15:40






  • 3





    Here's a simple solution that doesn't use jquery: developer.mozilla.org/en-US/docs/Web/API/FileReader/…

    – John Gilmer
    Aug 4 '16 at 19:22











  • angulartutorial.net/2017/02/…

    – Prashobh
    Feb 16 '17 at 14:18



















  • Note that unless you use Gears or another plugin you cannot manipulate the image inside the browser: code.google.com/p/chromium/issues/detail?id=32276

    – Steve-o
    Dec 16 '10 at 9:58











  • Check out this pure JavaScript approach, including its answer and there Ray Nicholus' comment for the final solution: stackoverflow.com/questions/16430016/…

    – Jonathan Root
    Oct 17 '13 at 15:05











  • Here's a nice detailed article with live demo codepedia.info/2015/06/…

    – Satinder singh
    Jul 27 '15 at 15:40






  • 3





    Here's a simple solution that doesn't use jquery: developer.mozilla.org/en-US/docs/Web/API/FileReader/…

    – John Gilmer
    Aug 4 '16 at 19:22











  • angulartutorial.net/2017/02/…

    – Prashobh
    Feb 16 '17 at 14:18

















Note that unless you use Gears or another plugin you cannot manipulate the image inside the browser: code.google.com/p/chromium/issues/detail?id=32276

– Steve-o
Dec 16 '10 at 9:58





Note that unless you use Gears or another plugin you cannot manipulate the image inside the browser: code.google.com/p/chromium/issues/detail?id=32276

– Steve-o
Dec 16 '10 at 9:58













Check out this pure JavaScript approach, including its answer and there Ray Nicholus' comment for the final solution: stackoverflow.com/questions/16430016/…

– Jonathan Root
Oct 17 '13 at 15:05





Check out this pure JavaScript approach, including its answer and there Ray Nicholus' comment for the final solution: stackoverflow.com/questions/16430016/…

– Jonathan Root
Oct 17 '13 at 15:05













Here's a nice detailed article with live demo codepedia.info/2015/06/…

– Satinder singh
Jul 27 '15 at 15:40





Here's a nice detailed article with live demo codepedia.info/2015/06/…

– Satinder singh
Jul 27 '15 at 15:40




3




3





Here's a simple solution that doesn't use jquery: developer.mozilla.org/en-US/docs/Web/API/FileReader/…

– John Gilmer
Aug 4 '16 at 19:22





Here's a simple solution that doesn't use jquery: developer.mozilla.org/en-US/docs/Web/API/FileReader/…

– John Gilmer
Aug 4 '16 at 19:22













angulartutorial.net/2017/02/…

– Prashobh
Feb 16 '17 at 14:18





angulartutorial.net/2017/02/…

– Prashobh
Feb 16 '17 at 14:18












18 Answers
18






active

oldest

votes


















2119














Please take a look at the sample code below:






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 src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>





Also, you can try this sample here.






share|improve this answer





















  • 2





    You can improve a little bit performance by define the reader once. jsfiddle.net/LvsYc/638

    – Jaider
    Sep 3 '13 at 14:45






  • 35





    Why use jQuery for ` $('#blah').attr('src', e.target.result);` when you could have simply done document.getElementById('blah').src=e.target.result)

    – EasyBB
    Jul 21 '14 at 19:26






  • 2





    I made a ReactJS implementation of this. Works like a charm. @kxc you should make an ajax call and send input.files[0] as data, see jQuery's doc.

    – Sumi Straessle
    Mar 13 '17 at 9:07








  • 2





    Why not use reader.result rather than e.target.result?

    – Liam Appleyard
    Apr 24 '18 at 10:44













  • @IvanBaev input.files[0] does not have the full path. How does FileReader locate the file?

    – Old Geezer
    Aug 30 '18 at 2:23



















258














There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL() on the File from your <input>. Pass this URL to img.src to tell the browser to load the provided image.



Here's an example:






<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
};
</script>





You can also use FileReader.readAsDataURL() to parse the file from your <input>. This will create a string in memory containing a base64 representation of the image.






<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
</script>








share|improve this answer





















  • 23





    Read carefully: readAsDataURL and createObjectURL will cache an image in the browser, then return a base64 encoded string which references the image location in cache. If browser cache is cleared, the base64 encoded string will no longer reference the image. The base64 string isn't actual image data, it's a url reference to the image, and you shouldn't save it to a database hoping to retrieve image data. I've recently made this mistake (about 3 minutes ago).

    – tfmontague
    Jan 13 '15 at 12:02













  • to avoid memory issues you should call URL.revokeObjectURL when you are done with your blob

    – Apolo
    Nov 20 '18 at 16:09





















159














One-liner solution:



The following code uses object URLs, which is much more efficient than data URL for viewing large images (A data URL is a huge string containing all of the file data, whereas an object URL, is just a short string referencing the file data in-memory):






<img id="blah" alt="your image" width="100" height="100" />

<input type="file"
onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">





Generated URL will be like:



blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345





share|improve this answer





















  • 4





    version notice: supports by IE10+ caniuse.com/#feat=bloburls

    – Raptor
    Jul 23 '15 at 6:58






  • 1





    @Raptor and so is the whole File API... (FileReader, input.files etc.) URL.createObjectURL is the way to go when dealing with user submitted files, it only creates an in-memory symlink to the real file on user's disk.

    – Kaiido
    Jul 2 '17 at 2:20











  • @cnlevy How can we access the files uploaded? Is it only possible to get it from the URL as you mentioned? To be specific, I'm using flask which already supports access of uploaded files. Is there some other way with this one-liner?

    – Abhishek Singh
    Dec 26 '18 at 13:16





















43














The answer of LeassTaTT works well in "standard" browsers like FF and Chrome.
The solution for IE exists, but looks different. Here description of cross-browser solution:



In HTML we need two preview elements, img for standard browsers and div for IE



HTML:



<img id="preview" 
src=""
alt=""
style="display:none; max-width: 160px; max-height: 120px; border: none;"/>

<div id="preview_ie"></div>


In CSS we specify the following IE specific thing:



CSS:



#preview_ie {
FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)
}


In HTML we include the standard and the IE-specific Javascripts:



<script type="text/javascript">
{% include "pic_preview.js" %}
</script>
<!--[if gte IE 7]>
<script type="text/javascript">
{% include "pic_preview_ie.js" %}
</script>




The pic_preview.js is the Javascript from the LeassTaTT's answer. Replace the $('#blah') whith the $('#preview') and add the $('#preview').show()



Now the IE specific Javascript (pic_preview_ie.js):



function readURL (imgFile) {    
var newPreview = document.getElementById('preview_ie');
newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;
newPreview.style.width = '160px';
newPreview.style.height = '120px';
}


That's is. Works in IE7, IE8, FF and Chrome. Please test in IE9 and report.
The idea of IE preview was found here:
http://forums.asp.net/t/1320559.aspx



http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85).aspx






share|improve this answer

































    22














    I have edited @Ivan's answer to display "No Preview Available" image, if it is not an image:



    function readURL(input) {
    var url = input.value;
    var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
    if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
    var reader = new FileReader();

    reader.onload = function (e) {
    $('.imagepreview').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
    }else{
    $('.imagepreview').attr('src', '/assets/no_preview.png');
    }
    }





    share|improve this answer































      16














      Here's a multiple files version, based on Ivan Baev's answer.



      The HTML



      <input type="file" multiple id="gallery-photo-add">
      <div class="gallery"></div>


      JavaScript / jQuery



      $(function() {
      // Multiple images preview in browser
      var imagesPreview = function(input, placeToInsertImagePreview) {

      if (input.files) {
      var filesAmount = input.files.length;

      for (i = 0; i < filesAmount; i++) {
      var reader = new FileReader();

      reader.onload = function(event) {
      $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
      }

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

      };

      $('#gallery-photo-add').on('change', function() {
      imagesPreview(this, 'div.gallery');
      });
      });


      Requires jQuery 1.8 due to the usage of $.parseHTML, which should help with XSS mitigation.



      This will work out of the box, and the only dependancy you need is jQuery.






      share|improve this answer

































        13














        Yes. It is possible.



        Html



        <input type="file" accept="image/*"  onchange="showMyImage(this)" />
        <br/>
        <img id="thumbnil" style="width:20%; margin-top:10px;" src="" alt="image"/>


        JS



         function showMyImage(fileInput) {
        var files = fileInput.files;
        for (var i = 0; i < files.length; i++) {
        var file = files[i];
        var imageType = /image.*/;
        if (!file.type.match(imageType)) {
        continue;
        }
        var img=document.getElementById("thumbnil");
        img.file = file;
        var reader = new FileReader();
        reader.onload = (function(aImg) {
        return function(e) {
        aImg.src = e.target.result;
        };
        })(img);
        reader.readAsDataURL(file);
        }
        }


        You can get Live Demo from here.






        share|improve this answer































          9














          Clean and simple
          JSfiddle



          This will be useful when you want The event to triggered indirectly from a div or a button.



          <img id="image-preview"  style="height:100px; width:100px;"  src="" >

          <input style="display:none" id="input-image-hidden" onchange="document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" type="file" accept="image/jpeg, image/png">

          <button onclick="HandleBrowseClick('input-image-hidden');" >UPLOAD IMAGE</button>


          <script type="text/javascript">
          function HandleBrowseClick(hidden_input_image)
          {
          var fileinputElement = document.getElementById(hidden_input_image);
          fileinputElement.click();
          }
          </script>





          share|improve this answer


























          • Just a note: I can't take credit for this but you can use <label> and avoid javascript for handling the button click altogether. Trigger File-input with pure HTML/CSS., and it's not hacky at all.

            – Regular Joe
            Oct 11 '17 at 20:27





















          6














          Example with multiple images using JavaScript (jQuery) and HTML5



          JavaScript (jQuery)



          function readURL(input) {
          for(var i =0; i< input.files.length; i++){
          if (input.files[i]) {
          var reader = new FileReader();

          reader.onload = function (e) {
          var img = $('<img id="dynamic">');
          img.attr('src', e.target.result);
          img.appendTo('#form1');
          }
          reader.readAsDataURL(input.files[i]);
          }
          }
          }

          $("#imgUpload").change(function(){
          readURL(this);
          });
          }


          Markup (HTML)



          <form id="form1" runat="server">
          <input type="file" id="imgUpload" multiple/>
          </form>





          share|improve this answer

































            5














            How about creating a function that loads the file and fires a custom event. Then attach a listener to the input. This way we have more flexibility to use the file, not just for previewing images.



            /**
            * @param {domElement} input - The input element
            * @param {string} typeData - The type of data to be return in the event object.
            */
            function loadFileFromInput(input,typeData) {
            var reader,
            fileLoadedEvent,
            files = input.files;

            if (files && files[0]) {
            reader = new FileReader();

            reader.onload = function (e) {
            fileLoadedEvent = new CustomEvent('fileLoaded',{
            detail:{
            data:reader.result,
            file:files[0]
            },
            bubbles:true,
            cancelable:true
            });
            input.dispatchEvent(fileLoadedEvent);
            }
            switch(typeData) {
            case 'arraybuffer':
            reader.readAsArrayBuffer(files[0]);
            break;
            case 'dataurl':
            reader.readAsDataURL(files[0]);
            break;
            case 'binarystring':
            reader.readAsBinaryString(files[0]);
            break;
            case 'text':
            reader.readAsText(files[0]);
            break;
            }
            }
            }
            function fileHandler (e) {
            var data = e.detail.data,
            fileInfo = e.detail.file;

            img.src = data;
            }
            var input = document.getElementById('inputId'),
            img = document.getElementById('imgId');

            input.onchange = function (e) {
            loadFileFromInput(e.target,'dataurl');
            };

            input.addEventListener('fileLoaded',fileHandler)


            Probably my code isn't as good as some users but I think you will get the point of it. Here you can see an example






            share|improve this answer

































              3














              Following is the working code.



              <input type='file' onchange="readURL(this);" /> 
              <img id="ShowImage" src="#" />


              Javascript:



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

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

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





              share|improve this answer































                2














                What about this solution?



                Just add the data attribute "data-type=editable" to an image tag like this:



                <img data-type="editable" id="companyLogo" src="http://www.coventrywebgraphicdesign.co.uk/wp-content/uploads/logo-here.jpg" height="300px" width="300px" />


                And the script to your project off course...



                function init() {
                $("img[data-type=editable]").each(function (i, e) {
                var _inputFile = $('<input/>')
                .attr('type', 'file')
                .attr('hidden', 'hidden')
                .attr('onchange', 'readImage()')
                .attr('data-image-placeholder', e.id);

                $(e.parentElement).append(_inputFile);

                $(e).on("click", _inputFile, triggerClick);
                });
                }

                function triggerClick(e) {
                e.data.click();
                }

                Element.prototype.readImage = function () {
                var _inputFile = this;
                if (_inputFile && _inputFile.files && _inputFile.files[0]) {
                var _fileReader = new FileReader();
                _fileReader.onload = function (e) {
                var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;
                var _img = $("#" + _imagePlaceholder);
                _img.attr("src", e.target.result);
                };
                _fileReader.readAsDataURL(_inputFile.files[0]);
                }
                };

                //
                // IIFE - Immediately Invoked Function Expression
                // https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
                (

                function (yourcode) {
                "use strict";
                // The global jQuery object is passed as a parameter
                yourcode(window.jQuery, window, document);
                }(

                function ($, window, document) {
                "use strict";
                // The $ is now locally scoped
                $(function () {
                // The DOM is ready!
                init();
                });

                // The rest of your code goes here!
                }));


                See demo at JSFiddle






                share|improve this answer































                  1














                  I have made a plugin which can generate the preview effect in IE 7+ thanks to the internet, but has few limitations. I put it into a github page so that its easier to get it






                  $(function () {
                  $("input[name=file1]").previewimage({
                  div: ".preview",
                  imgwidth: 180,
                  imgheight: 120
                  });
                  $("input[name=file2]").previewimage({
                  div: ".preview2",
                  imgwidth: 90,
                  imgheight: 90
                  });
                  });

                  .preview > div {
                  display: inline-block;
                  text-align:center;
                  }

                  .preview2 > div {
                  display: inline-block;
                  text-align:center;
                  }

                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
                  <script src="https://rawgit.com/andrewng330/PreviewImage/master/preview.image.min.js"></script>
                  Preview
                  <div class="preview"></div>
                  Preview2
                  <div class="preview2"></div>

                  <form action="#" method="POST" enctype="multipart/form-data">
                  <input type="file" name="file1">
                  <input type="file" name="file2">
                  <input type="submit">
                  </form>








                  share|improve this answer

































                    1














                    For Multiple image upload (Modification to the @IvanBaev's Solution)



                    function readURL(input) {
                    if (input.files && input.files[0]) {
                    var i;
                    for (i = 0; i < input.files.length; ++i) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                    $('#form1').append('<img src="'+e.target.result+'">');
                    }
                    reader.readAsDataURL(input.files[i]);
                    }
                    }
                    }


                    http://jsfiddle.net/LvsYc/12330/



                    Hope this helps someone.






                    share|improve this answer































                      0














                      It's my code.Support IE[6-9]、chrome 17+、firefox、Opera 11+、Maxthon3



                      HTML



                      <input type="file"  id="netBarBig"  onchange="changeFile(this)"  />
                      <img src="" id="imagePreview" style="width:120px;height:80px;" alt=""/>


                      javascript:






                      <script>

                      function previewImage(fileObj, imgPreviewId) {
                      var allowExtention = ".jpg,.bmp,.gif,.png"; //allowed to upload file type
                      document.getElementById("hfAllowPicSuffix").value;
                      var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
                      var browserVersion = window.navigator.userAgent.toUpperCase();
                      if (allowExtention.indexOf(extention) > -1) {
                      if (fileObj.files) {
                      if (window.FileReader) {
                      var reader = new FileReader();
                      reader.onload = function (e) {
                      document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
                      };
                      reader.readAsDataURL(fileObj.files[0]);
                      } else if (browserVersion.indexOf("SAFARI") > -1) {
                      alert("don't support Safari6.0 below broswer");
                      }
                      } else if (browserVersion.indexOf("MSIE") > -1) {
                      if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
                      document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                      } else {//ie[7-9]
                      fileObj.select();
                      fileObj.blur();
                      var newPreview = document.getElementById(imgPreviewId);

                      newPreview.style.border = "solid 1px #eeeeee";
                      newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
                      newPreview.style.display = "block";

                      }
                      } else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
                      var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox/([d.]+)/)[1]);
                      if (firefoxVersion < 7) {//firefox7 below
                      document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
                      } else {//firefox7.0+ 
                      document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
                      }
                      } else {
                      document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                      }
                      } else {
                      alert("only support" + allowExtention + "suffix");
                      fileObj.value = ""; //clear Selected file
                      if (browserVersion.indexOf("MSIE") > -1) {
                      fileObj.select();
                      document.selection.clear();
                      }

                      }
                      }
                      function changeFile(elem) {
                      //file object , preview img tag id
                      previewImage(elem,'imagePreview')
                      }

                      </script>








                      share|improve this answer































                        0














                        Try this






                        window.onload = function() {
                        if (window.File && window.FileList && window.FileReader) {
                        var filesInput = document.getElementById("uploadImage");
                        filesInput.addEventListener("change", function(event) {
                        var files = event.target.files;
                        var output = document.getElementById("result");
                        for (var i = 0; i < files.length; i++) {
                        var file = files[i];
                        if (!file.type.match('image'))
                        continue;
                        var picReader = new FileReader();
                        picReader.addEventListener("load", function(event) {
                        var picFile = event.target;
                        var div = document.createElement("div");
                        div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
                        "title='" + picFile.name + "'/>";
                        output.insertBefore(div, null);
                        });
                        picReader.readAsDataURL(file);
                        }

                        });
                        }
                        }

                        <input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
                        <div id="result" class="uploadPreview">








                        share|improve this answer































                          -1














                          function assignFilePreviews() {
                          $('input[data-previewable="true"]').change(function() {
                          var prvCnt = $(this).attr('data-preview-container');
                          if (prvCnt) {
                          if (this.files && this.files[0]) {
                          var reader = new FileReader();
                          reader.onload = function(e) {
                          var img = $('<img>');
                          img.attr('src', e.target.result);
                          img.error(function() {
                          $(prvCnt).html('');
                          });
                          $(prvCnt).html('');
                          img.appendTo(prvCnt);
                          }
                          reader.readAsDataURL(this.files[0]);
                          }
                          }
                          });
                          }
                          $(document).ready(function() {
                          assignFilePreviews();
                          });


                          HTML



                          <input type="file" data-previewable="true" data-preview-container=".prd-img-prv" />
                          <div class = "prd-img-prv"></div>


                          This also handles case when file with invalid type ( ex. pdf ) is choosen






                          share|improve this answer

































                            -2














                            for my app, with encryped GET url parameters, only this worked. I always got a TypeError: $(...) is null.
                            Taken from https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL






                            function previewFile() {
                            var preview = document.querySelector('img');
                            var file = document.querySelector('input[type=file]').files[0];
                            var reader = new FileReader();

                            reader.addEventListener("load", function () {
                            preview.src = reader.result;
                            }, false);

                            if (file) {
                            reader.readAsDataURL(file);
                            }
                            }

                            <input type="file" onchange="previewFile()"><br>
                            <img src="" height="200" alt="Image preview...">








                            share|improve this answer






















                              protected by Community Feb 11 '13 at 14:44



                              Thank you for your interest in this question.
                              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                              Would you like to answer one of these unanswered questions instead?














                              18 Answers
                              18






                              active

                              oldest

                              votes








                              18 Answers
                              18






                              active

                              oldest

                              votes









                              active

                              oldest

                              votes






                              active

                              oldest

                              votes









                              2119














                              Please take a look at the sample code below:






                              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 src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                              <form id="form1" runat="server">
                              <input type='file' id="imgInp" />
                              <img id="blah" src="#" alt="your image" />
                              </form>





                              Also, you can try this sample here.






                              share|improve this answer





















                              • 2





                                You can improve a little bit performance by define the reader once. jsfiddle.net/LvsYc/638

                                – Jaider
                                Sep 3 '13 at 14:45






                              • 35





                                Why use jQuery for ` $('#blah').attr('src', e.target.result);` when you could have simply done document.getElementById('blah').src=e.target.result)

                                – EasyBB
                                Jul 21 '14 at 19:26






                              • 2





                                I made a ReactJS implementation of this. Works like a charm. @kxc you should make an ajax call and send input.files[0] as data, see jQuery's doc.

                                – Sumi Straessle
                                Mar 13 '17 at 9:07








                              • 2





                                Why not use reader.result rather than e.target.result?

                                – Liam Appleyard
                                Apr 24 '18 at 10:44













                              • @IvanBaev input.files[0] does not have the full path. How does FileReader locate the file?

                                – Old Geezer
                                Aug 30 '18 at 2:23
















                              2119














                              Please take a look at the sample code below:






                              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 src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                              <form id="form1" runat="server">
                              <input type='file' id="imgInp" />
                              <img id="blah" src="#" alt="your image" />
                              </form>





                              Also, you can try this sample here.






                              share|improve this answer





















                              • 2





                                You can improve a little bit performance by define the reader once. jsfiddle.net/LvsYc/638

                                – Jaider
                                Sep 3 '13 at 14:45






                              • 35





                                Why use jQuery for ` $('#blah').attr('src', e.target.result);` when you could have simply done document.getElementById('blah').src=e.target.result)

                                – EasyBB
                                Jul 21 '14 at 19:26






                              • 2





                                I made a ReactJS implementation of this. Works like a charm. @kxc you should make an ajax call and send input.files[0] as data, see jQuery's doc.

                                – Sumi Straessle
                                Mar 13 '17 at 9:07








                              • 2





                                Why not use reader.result rather than e.target.result?

                                – Liam Appleyard
                                Apr 24 '18 at 10:44













                              • @IvanBaev input.files[0] does not have the full path. How does FileReader locate the file?

                                – Old Geezer
                                Aug 30 '18 at 2:23














                              2119












                              2119








                              2119







                              Please take a look at the sample code below:






                              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 src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                              <form id="form1" runat="server">
                              <input type='file' id="imgInp" />
                              <img id="blah" src="#" alt="your image" />
                              </form>





                              Also, you can try this sample here.






                              share|improve this answer















                              Please take a look at the sample code below:






                              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 src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                              <form id="form1" runat="server">
                              <input type='file' id="imgInp" />
                              <img id="blah" src="#" alt="your image" />
                              </form>





                              Also, you can try this sample here.






                              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 src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                              <form id="form1" runat="server">
                              <input type='file' id="imgInp" />
                              <img id="blah" src="#" alt="your image" />
                              </form>





                              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 src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                              <form id="form1" runat="server">
                              <input type='file' id="imgInp" />
                              <img id="blah" src="#" alt="your image" />
                              </form>






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Oct 20 '17 at 12:48









                              Paolo Forgia

                              4,57262849




                              4,57262849










                              answered Dec 16 '10 at 9:55









                              Ivan BaevIvan Baev

                              21.3k1116




                              21.3k1116








                              • 2





                                You can improve a little bit performance by define the reader once. jsfiddle.net/LvsYc/638

                                – Jaider
                                Sep 3 '13 at 14:45






                              • 35





                                Why use jQuery for ` $('#blah').attr('src', e.target.result);` when you could have simply done document.getElementById('blah').src=e.target.result)

                                – EasyBB
                                Jul 21 '14 at 19:26






                              • 2





                                I made a ReactJS implementation of this. Works like a charm. @kxc you should make an ajax call and send input.files[0] as data, see jQuery's doc.

                                – Sumi Straessle
                                Mar 13 '17 at 9:07








                              • 2





                                Why not use reader.result rather than e.target.result?

                                – Liam Appleyard
                                Apr 24 '18 at 10:44













                              • @IvanBaev input.files[0] does not have the full path. How does FileReader locate the file?

                                – Old Geezer
                                Aug 30 '18 at 2:23














                              • 2





                                You can improve a little bit performance by define the reader once. jsfiddle.net/LvsYc/638

                                – Jaider
                                Sep 3 '13 at 14:45






                              • 35





                                Why use jQuery for ` $('#blah').attr('src', e.target.result);` when you could have simply done document.getElementById('blah').src=e.target.result)

                                – EasyBB
                                Jul 21 '14 at 19:26






                              • 2





                                I made a ReactJS implementation of this. Works like a charm. @kxc you should make an ajax call and send input.files[0] as data, see jQuery's doc.

                                – Sumi Straessle
                                Mar 13 '17 at 9:07








                              • 2





                                Why not use reader.result rather than e.target.result?

                                – Liam Appleyard
                                Apr 24 '18 at 10:44













                              • @IvanBaev input.files[0] does not have the full path. How does FileReader locate the file?

                                – Old Geezer
                                Aug 30 '18 at 2:23








                              2




                              2





                              You can improve a little bit performance by define the reader once. jsfiddle.net/LvsYc/638

                              – Jaider
                              Sep 3 '13 at 14:45





                              You can improve a little bit performance by define the reader once. jsfiddle.net/LvsYc/638

                              – Jaider
                              Sep 3 '13 at 14:45




                              35




                              35





                              Why use jQuery for ` $('#blah').attr('src', e.target.result);` when you could have simply done document.getElementById('blah').src=e.target.result)

                              – EasyBB
                              Jul 21 '14 at 19:26





                              Why use jQuery for ` $('#blah').attr('src', e.target.result);` when you could have simply done document.getElementById('blah').src=e.target.result)

                              – EasyBB
                              Jul 21 '14 at 19:26




                              2




                              2





                              I made a ReactJS implementation of this. Works like a charm. @kxc you should make an ajax call and send input.files[0] as data, see jQuery's doc.

                              – Sumi Straessle
                              Mar 13 '17 at 9:07







                              I made a ReactJS implementation of this. Works like a charm. @kxc you should make an ajax call and send input.files[0] as data, see jQuery's doc.

                              – Sumi Straessle
                              Mar 13 '17 at 9:07






                              2




                              2





                              Why not use reader.result rather than e.target.result?

                              – Liam Appleyard
                              Apr 24 '18 at 10:44







                              Why not use reader.result rather than e.target.result?

                              – Liam Appleyard
                              Apr 24 '18 at 10:44















                              @IvanBaev input.files[0] does not have the full path. How does FileReader locate the file?

                              – Old Geezer
                              Aug 30 '18 at 2:23





                              @IvanBaev input.files[0] does not have the full path. How does FileReader locate the file?

                              – Old Geezer
                              Aug 30 '18 at 2:23













                              258














                              There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL() on the File from your <input>. Pass this URL to img.src to tell the browser to load the provided image.



                              Here's an example:






                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var output = document.getElementById('output');
                              output.src = URL.createObjectURL(event.target.files[0]);
                              };
                              </script>





                              You can also use FileReader.readAsDataURL() to parse the file from your <input>. This will create a string in memory containing a base64 representation of the image.






                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var reader = new FileReader();
                              reader.onload = function(){
                              var output = document.getElementById('output');
                              output.src = reader.result;
                              };
                              reader.readAsDataURL(event.target.files[0]);
                              };
                              </script>








                              share|improve this answer





















                              • 23





                                Read carefully: readAsDataURL and createObjectURL will cache an image in the browser, then return a base64 encoded string which references the image location in cache. If browser cache is cleared, the base64 encoded string will no longer reference the image. The base64 string isn't actual image data, it's a url reference to the image, and you shouldn't save it to a database hoping to retrieve image data. I've recently made this mistake (about 3 minutes ago).

                                – tfmontague
                                Jan 13 '15 at 12:02













                              • to avoid memory issues you should call URL.revokeObjectURL when you are done with your blob

                                – Apolo
                                Nov 20 '18 at 16:09


















                              258














                              There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL() on the File from your <input>. Pass this URL to img.src to tell the browser to load the provided image.



                              Here's an example:






                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var output = document.getElementById('output');
                              output.src = URL.createObjectURL(event.target.files[0]);
                              };
                              </script>





                              You can also use FileReader.readAsDataURL() to parse the file from your <input>. This will create a string in memory containing a base64 representation of the image.






                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var reader = new FileReader();
                              reader.onload = function(){
                              var output = document.getElementById('output');
                              output.src = reader.result;
                              };
                              reader.readAsDataURL(event.target.files[0]);
                              };
                              </script>








                              share|improve this answer





















                              • 23





                                Read carefully: readAsDataURL and createObjectURL will cache an image in the browser, then return a base64 encoded string which references the image location in cache. If browser cache is cleared, the base64 encoded string will no longer reference the image. The base64 string isn't actual image data, it's a url reference to the image, and you shouldn't save it to a database hoping to retrieve image data. I've recently made this mistake (about 3 minutes ago).

                                – tfmontague
                                Jan 13 '15 at 12:02













                              • to avoid memory issues you should call URL.revokeObjectURL when you are done with your blob

                                – Apolo
                                Nov 20 '18 at 16:09
















                              258












                              258








                              258







                              There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL() on the File from your <input>. Pass this URL to img.src to tell the browser to load the provided image.



                              Here's an example:






                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var output = document.getElementById('output');
                              output.src = URL.createObjectURL(event.target.files[0]);
                              };
                              </script>





                              You can also use FileReader.readAsDataURL() to parse the file from your <input>. This will create a string in memory containing a base64 representation of the image.






                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var reader = new FileReader();
                              reader.onload = function(){
                              var output = document.getElementById('output');
                              output.src = reader.result;
                              };
                              reader.readAsDataURL(event.target.files[0]);
                              };
                              </script>








                              share|improve this answer















                              There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL() on the File from your <input>. Pass this URL to img.src to tell the browser to load the provided image.



                              Here's an example:






                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var output = document.getElementById('output');
                              output.src = URL.createObjectURL(event.target.files[0]);
                              };
                              </script>





                              You can also use FileReader.readAsDataURL() to parse the file from your <input>. This will create a string in memory containing a base64 representation of the image.






                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var reader = new FileReader();
                              reader.onload = function(){
                              var output = document.getElementById('output');
                              output.src = reader.result;
                              };
                              reader.readAsDataURL(event.target.files[0]);
                              };
                              </script>








                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var output = document.getElementById('output');
                              output.src = URL.createObjectURL(event.target.files[0]);
                              };
                              </script>





                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var output = document.getElementById('output');
                              output.src = URL.createObjectURL(event.target.files[0]);
                              };
                              </script>





                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var reader = new FileReader();
                              reader.onload = function(){
                              var output = document.getElementById('output');
                              output.src = reader.result;
                              };
                              reader.readAsDataURL(event.target.files[0]);
                              };
                              </script>





                              <input type="file" accept="image/*" onchange="loadFile(event)">
                              <img id="output"/>
                              <script>
                              var loadFile = function(event) {
                              var reader = new FileReader();
                              reader.onload = function(){
                              var output = document.getElementById('output');
                              output.src = reader.result;
                              };
                              reader.readAsDataURL(event.target.files[0]);
                              };
                              </script>






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jan 13 '15 at 7:43

























                              answered Nov 27 '14 at 8:17









                              nkronnkron

                              10.5k32118




                              10.5k32118








                              • 23





                                Read carefully: readAsDataURL and createObjectURL will cache an image in the browser, then return a base64 encoded string which references the image location in cache. If browser cache is cleared, the base64 encoded string will no longer reference the image. The base64 string isn't actual image data, it's a url reference to the image, and you shouldn't save it to a database hoping to retrieve image data. I've recently made this mistake (about 3 minutes ago).

                                – tfmontague
                                Jan 13 '15 at 12:02













                              • to avoid memory issues you should call URL.revokeObjectURL when you are done with your blob

                                – Apolo
                                Nov 20 '18 at 16:09
















                              • 23





                                Read carefully: readAsDataURL and createObjectURL will cache an image in the browser, then return a base64 encoded string which references the image location in cache. If browser cache is cleared, the base64 encoded string will no longer reference the image. The base64 string isn't actual image data, it's a url reference to the image, and you shouldn't save it to a database hoping to retrieve image data. I've recently made this mistake (about 3 minutes ago).

                                – tfmontague
                                Jan 13 '15 at 12:02













                              • to avoid memory issues you should call URL.revokeObjectURL when you are done with your blob

                                – Apolo
                                Nov 20 '18 at 16:09










                              23




                              23





                              Read carefully: readAsDataURL and createObjectURL will cache an image in the browser, then return a base64 encoded string which references the image location in cache. If browser cache is cleared, the base64 encoded string will no longer reference the image. The base64 string isn't actual image data, it's a url reference to the image, and you shouldn't save it to a database hoping to retrieve image data. I've recently made this mistake (about 3 minutes ago).

                              – tfmontague
                              Jan 13 '15 at 12:02







                              Read carefully: readAsDataURL and createObjectURL will cache an image in the browser, then return a base64 encoded string which references the image location in cache. If browser cache is cleared, the base64 encoded string will no longer reference the image. The base64 string isn't actual image data, it's a url reference to the image, and you shouldn't save it to a database hoping to retrieve image data. I've recently made this mistake (about 3 minutes ago).

                              – tfmontague
                              Jan 13 '15 at 12:02















                              to avoid memory issues you should call URL.revokeObjectURL when you are done with your blob

                              – Apolo
                              Nov 20 '18 at 16:09







                              to avoid memory issues you should call URL.revokeObjectURL when you are done with your blob

                              – Apolo
                              Nov 20 '18 at 16:09













                              159














                              One-liner solution:



                              The following code uses object URLs, which is much more efficient than data URL for viewing large images (A data URL is a huge string containing all of the file data, whereas an object URL, is just a short string referencing the file data in-memory):






                              <img id="blah" alt="your image" width="100" height="100" />

                              <input type="file"
                              onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">





                              Generated URL will be like:



                              blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345





                              share|improve this answer





















                              • 4





                                version notice: supports by IE10+ caniuse.com/#feat=bloburls

                                – Raptor
                                Jul 23 '15 at 6:58






                              • 1





                                @Raptor and so is the whole File API... (FileReader, input.files etc.) URL.createObjectURL is the way to go when dealing with user submitted files, it only creates an in-memory symlink to the real file on user's disk.

                                – Kaiido
                                Jul 2 '17 at 2:20











                              • @cnlevy How can we access the files uploaded? Is it only possible to get it from the URL as you mentioned? To be specific, I'm using flask which already supports access of uploaded files. Is there some other way with this one-liner?

                                – Abhishek Singh
                                Dec 26 '18 at 13:16


















                              159














                              One-liner solution:



                              The following code uses object URLs, which is much more efficient than data URL for viewing large images (A data URL is a huge string containing all of the file data, whereas an object URL, is just a short string referencing the file data in-memory):






                              <img id="blah" alt="your image" width="100" height="100" />

                              <input type="file"
                              onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">





                              Generated URL will be like:



                              blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345





                              share|improve this answer





















                              • 4





                                version notice: supports by IE10+ caniuse.com/#feat=bloburls

                                – Raptor
                                Jul 23 '15 at 6:58






                              • 1





                                @Raptor and so is the whole File API... (FileReader, input.files etc.) URL.createObjectURL is the way to go when dealing with user submitted files, it only creates an in-memory symlink to the real file on user's disk.

                                – Kaiido
                                Jul 2 '17 at 2:20











                              • @cnlevy How can we access the files uploaded? Is it only possible to get it from the URL as you mentioned? To be specific, I'm using flask which already supports access of uploaded files. Is there some other way with this one-liner?

                                – Abhishek Singh
                                Dec 26 '18 at 13:16
















                              159












                              159








                              159







                              One-liner solution:



                              The following code uses object URLs, which is much more efficient than data URL for viewing large images (A data URL is a huge string containing all of the file data, whereas an object URL, is just a short string referencing the file data in-memory):






                              <img id="blah" alt="your image" width="100" height="100" />

                              <input type="file"
                              onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">





                              Generated URL will be like:



                              blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345





                              share|improve this answer















                              One-liner solution:



                              The following code uses object URLs, which is much more efficient than data URL for viewing large images (A data URL is a huge string containing all of the file data, whereas an object URL, is just a short string referencing the file data in-memory):






                              <img id="blah" alt="your image" width="100" height="100" />

                              <input type="file"
                              onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">





                              Generated URL will be like:



                              blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345





                              <img id="blah" alt="your image" width="100" height="100" />

                              <input type="file"
                              onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">





                              <img id="blah" alt="your image" width="100" height="100" />

                              <input type="file"
                              onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jun 7 '18 at 13:21

























                              answered Nov 18 '14 at 20:00









                              cnlevycnlevy

                              4,07621317




                              4,07621317








                              • 4





                                version notice: supports by IE10+ caniuse.com/#feat=bloburls

                                – Raptor
                                Jul 23 '15 at 6:58






                              • 1





                                @Raptor and so is the whole File API... (FileReader, input.files etc.) URL.createObjectURL is the way to go when dealing with user submitted files, it only creates an in-memory symlink to the real file on user's disk.

                                – Kaiido
                                Jul 2 '17 at 2:20











                              • @cnlevy How can we access the files uploaded? Is it only possible to get it from the URL as you mentioned? To be specific, I'm using flask which already supports access of uploaded files. Is there some other way with this one-liner?

                                – Abhishek Singh
                                Dec 26 '18 at 13:16
















                              • 4





                                version notice: supports by IE10+ caniuse.com/#feat=bloburls

                                – Raptor
                                Jul 23 '15 at 6:58






                              • 1





                                @Raptor and so is the whole File API... (FileReader, input.files etc.) URL.createObjectURL is the way to go when dealing with user submitted files, it only creates an in-memory symlink to the real file on user's disk.

                                – Kaiido
                                Jul 2 '17 at 2:20











                              • @cnlevy How can we access the files uploaded? Is it only possible to get it from the URL as you mentioned? To be specific, I'm using flask which already supports access of uploaded files. Is there some other way with this one-liner?

                                – Abhishek Singh
                                Dec 26 '18 at 13:16










                              4




                              4





                              version notice: supports by IE10+ caniuse.com/#feat=bloburls

                              – Raptor
                              Jul 23 '15 at 6:58





                              version notice: supports by IE10+ caniuse.com/#feat=bloburls

                              – Raptor
                              Jul 23 '15 at 6:58




                              1




                              1





                              @Raptor and so is the whole File API... (FileReader, input.files etc.) URL.createObjectURL is the way to go when dealing with user submitted files, it only creates an in-memory symlink to the real file on user's disk.

                              – Kaiido
                              Jul 2 '17 at 2:20





                              @Raptor and so is the whole File API... (FileReader, input.files etc.) URL.createObjectURL is the way to go when dealing with user submitted files, it only creates an in-memory symlink to the real file on user's disk.

                              – Kaiido
                              Jul 2 '17 at 2:20













                              @cnlevy How can we access the files uploaded? Is it only possible to get it from the URL as you mentioned? To be specific, I'm using flask which already supports access of uploaded files. Is there some other way with this one-liner?

                              – Abhishek Singh
                              Dec 26 '18 at 13:16







                              @cnlevy How can we access the files uploaded? Is it only possible to get it from the URL as you mentioned? To be specific, I'm using flask which already supports access of uploaded files. Is there some other way with this one-liner?

                              – Abhishek Singh
                              Dec 26 '18 at 13:16













                              43














                              The answer of LeassTaTT works well in "standard" browsers like FF and Chrome.
                              The solution for IE exists, but looks different. Here description of cross-browser solution:



                              In HTML we need two preview elements, img for standard browsers and div for IE



                              HTML:



                              <img id="preview" 
                              src=""
                              alt=""
                              style="display:none; max-width: 160px; max-height: 120px; border: none;"/>

                              <div id="preview_ie"></div>


                              In CSS we specify the following IE specific thing:



                              CSS:



                              #preview_ie {
                              FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)
                              }


                              In HTML we include the standard and the IE-specific Javascripts:



                              <script type="text/javascript">
                              {% include "pic_preview.js" %}
                              </script>
                              <!--[if gte IE 7]>
                              <script type="text/javascript">
                              {% include "pic_preview_ie.js" %}
                              </script>




                              The pic_preview.js is the Javascript from the LeassTaTT's answer. Replace the $('#blah') whith the $('#preview') and add the $('#preview').show()



                              Now the IE specific Javascript (pic_preview_ie.js):



                              function readURL (imgFile) {    
                              var newPreview = document.getElementById('preview_ie');
                              newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;
                              newPreview.style.width = '160px';
                              newPreview.style.height = '120px';
                              }


                              That's is. Works in IE7, IE8, FF and Chrome. Please test in IE9 and report.
                              The idea of IE preview was found here:
                              http://forums.asp.net/t/1320559.aspx



                              http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85).aspx






                              share|improve this answer






























                                43














                                The answer of LeassTaTT works well in "standard" browsers like FF and Chrome.
                                The solution for IE exists, but looks different. Here description of cross-browser solution:



                                In HTML we need two preview elements, img for standard browsers and div for IE



                                HTML:



                                <img id="preview" 
                                src=""
                                alt=""
                                style="display:none; max-width: 160px; max-height: 120px; border: none;"/>

                                <div id="preview_ie"></div>


                                In CSS we specify the following IE specific thing:



                                CSS:



                                #preview_ie {
                                FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)
                                }


                                In HTML we include the standard and the IE-specific Javascripts:



                                <script type="text/javascript">
                                {% include "pic_preview.js" %}
                                </script>
                                <!--[if gte IE 7]>
                                <script type="text/javascript">
                                {% include "pic_preview_ie.js" %}
                                </script>




                                The pic_preview.js is the Javascript from the LeassTaTT's answer. Replace the $('#blah') whith the $('#preview') and add the $('#preview').show()



                                Now the IE specific Javascript (pic_preview_ie.js):



                                function readURL (imgFile) {    
                                var newPreview = document.getElementById('preview_ie');
                                newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;
                                newPreview.style.width = '160px';
                                newPreview.style.height = '120px';
                                }


                                That's is. Works in IE7, IE8, FF and Chrome. Please test in IE9 and report.
                                The idea of IE preview was found here:
                                http://forums.asp.net/t/1320559.aspx



                                http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85).aspx






                                share|improve this answer




























                                  43












                                  43








                                  43







                                  The answer of LeassTaTT works well in "standard" browsers like FF and Chrome.
                                  The solution for IE exists, but looks different. Here description of cross-browser solution:



                                  In HTML we need two preview elements, img for standard browsers and div for IE



                                  HTML:



                                  <img id="preview" 
                                  src=""
                                  alt=""
                                  style="display:none; max-width: 160px; max-height: 120px; border: none;"/>

                                  <div id="preview_ie"></div>


                                  In CSS we specify the following IE specific thing:



                                  CSS:



                                  #preview_ie {
                                  FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)
                                  }


                                  In HTML we include the standard and the IE-specific Javascripts:



                                  <script type="text/javascript">
                                  {% include "pic_preview.js" %}
                                  </script>
                                  <!--[if gte IE 7]>
                                  <script type="text/javascript">
                                  {% include "pic_preview_ie.js" %}
                                  </script>




                                  The pic_preview.js is the Javascript from the LeassTaTT's answer. Replace the $('#blah') whith the $('#preview') and add the $('#preview').show()



                                  Now the IE specific Javascript (pic_preview_ie.js):



                                  function readURL (imgFile) {    
                                  var newPreview = document.getElementById('preview_ie');
                                  newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;
                                  newPreview.style.width = '160px';
                                  newPreview.style.height = '120px';
                                  }


                                  That's is. Works in IE7, IE8, FF and Chrome. Please test in IE9 and report.
                                  The idea of IE preview was found here:
                                  http://forums.asp.net/t/1320559.aspx



                                  http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85).aspx






                                  share|improve this answer















                                  The answer of LeassTaTT works well in "standard" browsers like FF and Chrome.
                                  The solution for IE exists, but looks different. Here description of cross-browser solution:



                                  In HTML we need two preview elements, img for standard browsers and div for IE



                                  HTML:



                                  <img id="preview" 
                                  src=""
                                  alt=""
                                  style="display:none; max-width: 160px; max-height: 120px; border: none;"/>

                                  <div id="preview_ie"></div>


                                  In CSS we specify the following IE specific thing:



                                  CSS:



                                  #preview_ie {
                                  FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)
                                  }


                                  In HTML we include the standard and the IE-specific Javascripts:



                                  <script type="text/javascript">
                                  {% include "pic_preview.js" %}
                                  </script>
                                  <!--[if gte IE 7]>
                                  <script type="text/javascript">
                                  {% include "pic_preview_ie.js" %}
                                  </script>




                                  The pic_preview.js is the Javascript from the LeassTaTT's answer. Replace the $('#blah') whith the $('#preview') and add the $('#preview').show()



                                  Now the IE specific Javascript (pic_preview_ie.js):



                                  function readURL (imgFile) {    
                                  var newPreview = document.getElementById('preview_ie');
                                  newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;
                                  newPreview.style.width = '160px';
                                  newPreview.style.height = '120px';
                                  }


                                  That's is. Works in IE7, IE8, FF and Chrome. Please test in IE9 and report.
                                  The idea of IE preview was found here:
                                  http://forums.asp.net/t/1320559.aspx



                                  http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85).aspx







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Aug 14 '15 at 11:30









                                  Balthazar

                                  30.4k106287




                                  30.4k106287










                                  answered Dec 24 '11 at 11:58









                                  Dmitri DmitriDmitri Dmitri

                                  54743




                                  54743























                                      22














                                      I have edited @Ivan's answer to display "No Preview Available" image, if it is not an image:



                                      function readURL(input) {
                                      var url = input.value;
                                      var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
                                      if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
                                      var reader = new FileReader();

                                      reader.onload = function (e) {
                                      $('.imagepreview').attr('src', e.target.result);
                                      }

                                      reader.readAsDataURL(input.files[0]);
                                      }else{
                                      $('.imagepreview').attr('src', '/assets/no_preview.png');
                                      }
                                      }





                                      share|improve this answer




























                                        22














                                        I have edited @Ivan's answer to display "No Preview Available" image, if it is not an image:



                                        function readURL(input) {
                                        var url = input.value;
                                        var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
                                        if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
                                        var reader = new FileReader();

                                        reader.onload = function (e) {
                                        $('.imagepreview').attr('src', e.target.result);
                                        }

                                        reader.readAsDataURL(input.files[0]);
                                        }else{
                                        $('.imagepreview').attr('src', '/assets/no_preview.png');
                                        }
                                        }





                                        share|improve this answer


























                                          22












                                          22








                                          22







                                          I have edited @Ivan's answer to display "No Preview Available" image, if it is not an image:



                                          function readURL(input) {
                                          var url = input.value;
                                          var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
                                          if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
                                          var reader = new FileReader();

                                          reader.onload = function (e) {
                                          $('.imagepreview').attr('src', e.target.result);
                                          }

                                          reader.readAsDataURL(input.files[0]);
                                          }else{
                                          $('.imagepreview').attr('src', '/assets/no_preview.png');
                                          }
                                          }





                                          share|improve this answer













                                          I have edited @Ivan's answer to display "No Preview Available" image, if it is not an image:



                                          function readURL(input) {
                                          var url = input.value;
                                          var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
                                          if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
                                          var reader = new FileReader();

                                          reader.onload = function (e) {
                                          $('.imagepreview').attr('src', e.target.result);
                                          }

                                          reader.readAsDataURL(input.files[0]);
                                          }else{
                                          $('.imagepreview').attr('src', '/assets/no_preview.png');
                                          }
                                          }






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Jun 5 '14 at 6:23









                                          Sachin PrasadSachin Prasad

                                          3,53794182




                                          3,53794182























                                              16














                                              Here's a multiple files version, based on Ivan Baev's answer.



                                              The HTML



                                              <input type="file" multiple id="gallery-photo-add">
                                              <div class="gallery"></div>


                                              JavaScript / jQuery



                                              $(function() {
                                              // Multiple images preview in browser
                                              var imagesPreview = function(input, placeToInsertImagePreview) {

                                              if (input.files) {
                                              var filesAmount = input.files.length;

                                              for (i = 0; i < filesAmount; i++) {
                                              var reader = new FileReader();

                                              reader.onload = function(event) {
                                              $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                                              }

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

                                              };

                                              $('#gallery-photo-add').on('change', function() {
                                              imagesPreview(this, 'div.gallery');
                                              });
                                              });


                                              Requires jQuery 1.8 due to the usage of $.parseHTML, which should help with XSS mitigation.



                                              This will work out of the box, and the only dependancy you need is jQuery.






                                              share|improve this answer






























                                                16














                                                Here's a multiple files version, based on Ivan Baev's answer.



                                                The HTML



                                                <input type="file" multiple id="gallery-photo-add">
                                                <div class="gallery"></div>


                                                JavaScript / jQuery



                                                $(function() {
                                                // Multiple images preview in browser
                                                var imagesPreview = function(input, placeToInsertImagePreview) {

                                                if (input.files) {
                                                var filesAmount = input.files.length;

                                                for (i = 0; i < filesAmount; i++) {
                                                var reader = new FileReader();

                                                reader.onload = function(event) {
                                                $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                                                }

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

                                                };

                                                $('#gallery-photo-add').on('change', function() {
                                                imagesPreview(this, 'div.gallery');
                                                });
                                                });


                                                Requires jQuery 1.8 due to the usage of $.parseHTML, which should help with XSS mitigation.



                                                This will work out of the box, and the only dependancy you need is jQuery.






                                                share|improve this answer




























                                                  16












                                                  16








                                                  16







                                                  Here's a multiple files version, based on Ivan Baev's answer.



                                                  The HTML



                                                  <input type="file" multiple id="gallery-photo-add">
                                                  <div class="gallery"></div>


                                                  JavaScript / jQuery



                                                  $(function() {
                                                  // Multiple images preview in browser
                                                  var imagesPreview = function(input, placeToInsertImagePreview) {

                                                  if (input.files) {
                                                  var filesAmount = input.files.length;

                                                  for (i = 0; i < filesAmount; i++) {
                                                  var reader = new FileReader();

                                                  reader.onload = function(event) {
                                                  $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                                                  }

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

                                                  };

                                                  $('#gallery-photo-add').on('change', function() {
                                                  imagesPreview(this, 'div.gallery');
                                                  });
                                                  });


                                                  Requires jQuery 1.8 due to the usage of $.parseHTML, which should help with XSS mitigation.



                                                  This will work out of the box, and the only dependancy you need is jQuery.






                                                  share|improve this answer















                                                  Here's a multiple files version, based on Ivan Baev's answer.



                                                  The HTML



                                                  <input type="file" multiple id="gallery-photo-add">
                                                  <div class="gallery"></div>


                                                  JavaScript / jQuery



                                                  $(function() {
                                                  // Multiple images preview in browser
                                                  var imagesPreview = function(input, placeToInsertImagePreview) {

                                                  if (input.files) {
                                                  var filesAmount = input.files.length;

                                                  for (i = 0; i < filesAmount; i++) {
                                                  var reader = new FileReader();

                                                  reader.onload = function(event) {
                                                  $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                                                  }

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

                                                  };

                                                  $('#gallery-photo-add').on('change', function() {
                                                  imagesPreview(this, 'div.gallery');
                                                  });
                                                  });


                                                  Requires jQuery 1.8 due to the usage of $.parseHTML, which should help with XSS mitigation.



                                                  This will work out of the box, and the only dependancy you need is jQuery.







                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Apr 6 '17 at 17:27

























                                                  answered Dec 14 '15 at 15:30









                                                  Nino ŠkopacNino Škopac

                                                  2,38812037




                                                  2,38812037























                                                      13














                                                      Yes. It is possible.



                                                      Html



                                                      <input type="file" accept="image/*"  onchange="showMyImage(this)" />
                                                      <br/>
                                                      <img id="thumbnil" style="width:20%; margin-top:10px;" src="" alt="image"/>


                                                      JS



                                                       function showMyImage(fileInput) {
                                                      var files = fileInput.files;
                                                      for (var i = 0; i < files.length; i++) {
                                                      var file = files[i];
                                                      var imageType = /image.*/;
                                                      if (!file.type.match(imageType)) {
                                                      continue;
                                                      }
                                                      var img=document.getElementById("thumbnil");
                                                      img.file = file;
                                                      var reader = new FileReader();
                                                      reader.onload = (function(aImg) {
                                                      return function(e) {
                                                      aImg.src = e.target.result;
                                                      };
                                                      })(img);
                                                      reader.readAsDataURL(file);
                                                      }
                                                      }


                                                      You can get Live Demo from here.






                                                      share|improve this answer




























                                                        13














                                                        Yes. It is possible.



                                                        Html



                                                        <input type="file" accept="image/*"  onchange="showMyImage(this)" />
                                                        <br/>
                                                        <img id="thumbnil" style="width:20%; margin-top:10px;" src="" alt="image"/>


                                                        JS



                                                         function showMyImage(fileInput) {
                                                        var files = fileInput.files;
                                                        for (var i = 0; i < files.length; i++) {
                                                        var file = files[i];
                                                        var imageType = /image.*/;
                                                        if (!file.type.match(imageType)) {
                                                        continue;
                                                        }
                                                        var img=document.getElementById("thumbnil");
                                                        img.file = file;
                                                        var reader = new FileReader();
                                                        reader.onload = (function(aImg) {
                                                        return function(e) {
                                                        aImg.src = e.target.result;
                                                        };
                                                        })(img);
                                                        reader.readAsDataURL(file);
                                                        }
                                                        }


                                                        You can get Live Demo from here.






                                                        share|improve this answer


























                                                          13












                                                          13








                                                          13







                                                          Yes. It is possible.



                                                          Html



                                                          <input type="file" accept="image/*"  onchange="showMyImage(this)" />
                                                          <br/>
                                                          <img id="thumbnil" style="width:20%; margin-top:10px;" src="" alt="image"/>


                                                          JS



                                                           function showMyImage(fileInput) {
                                                          var files = fileInput.files;
                                                          for (var i = 0; i < files.length; i++) {
                                                          var file = files[i];
                                                          var imageType = /image.*/;
                                                          if (!file.type.match(imageType)) {
                                                          continue;
                                                          }
                                                          var img=document.getElementById("thumbnil");
                                                          img.file = file;
                                                          var reader = new FileReader();
                                                          reader.onload = (function(aImg) {
                                                          return function(e) {
                                                          aImg.src = e.target.result;
                                                          };
                                                          })(img);
                                                          reader.readAsDataURL(file);
                                                          }
                                                          }


                                                          You can get Live Demo from here.






                                                          share|improve this answer













                                                          Yes. It is possible.



                                                          Html



                                                          <input type="file" accept="image/*"  onchange="showMyImage(this)" />
                                                          <br/>
                                                          <img id="thumbnil" style="width:20%; margin-top:10px;" src="" alt="image"/>


                                                          JS



                                                           function showMyImage(fileInput) {
                                                          var files = fileInput.files;
                                                          for (var i = 0; i < files.length; i++) {
                                                          var file = files[i];
                                                          var imageType = /image.*/;
                                                          if (!file.type.match(imageType)) {
                                                          continue;
                                                          }
                                                          var img=document.getElementById("thumbnil");
                                                          img.file = file;
                                                          var reader = new FileReader();
                                                          reader.onload = (function(aImg) {
                                                          return function(e) {
                                                          aImg.src = e.target.result;
                                                          };
                                                          })(img);
                                                          reader.readAsDataURL(file);
                                                          }
                                                          }


                                                          You can get Live Demo from here.







                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Jul 25 '14 at 11:20









                                                          Md. RahmanMd. Rahman

                                                          1,5241014




                                                          1,5241014























                                                              9














                                                              Clean and simple
                                                              JSfiddle



                                                              This will be useful when you want The event to triggered indirectly from a div or a button.



                                                              <img id="image-preview"  style="height:100px; width:100px;"  src="" >

                                                              <input style="display:none" id="input-image-hidden" onchange="document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" type="file" accept="image/jpeg, image/png">

                                                              <button onclick="HandleBrowseClick('input-image-hidden');" >UPLOAD IMAGE</button>


                                                              <script type="text/javascript">
                                                              function HandleBrowseClick(hidden_input_image)
                                                              {
                                                              var fileinputElement = document.getElementById(hidden_input_image);
                                                              fileinputElement.click();
                                                              }
                                                              </script>





                                                              share|improve this answer


























                                                              • Just a note: I can't take credit for this but you can use <label> and avoid javascript for handling the button click altogether. Trigger File-input with pure HTML/CSS., and it's not hacky at all.

                                                                – Regular Joe
                                                                Oct 11 '17 at 20:27


















                                                              9














                                                              Clean and simple
                                                              JSfiddle



                                                              This will be useful when you want The event to triggered indirectly from a div or a button.



                                                              <img id="image-preview"  style="height:100px; width:100px;"  src="" >

                                                              <input style="display:none" id="input-image-hidden" onchange="document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" type="file" accept="image/jpeg, image/png">

                                                              <button onclick="HandleBrowseClick('input-image-hidden');" >UPLOAD IMAGE</button>


                                                              <script type="text/javascript">
                                                              function HandleBrowseClick(hidden_input_image)
                                                              {
                                                              var fileinputElement = document.getElementById(hidden_input_image);
                                                              fileinputElement.click();
                                                              }
                                                              </script>





                                                              share|improve this answer


























                                                              • Just a note: I can't take credit for this but you can use <label> and avoid javascript for handling the button click altogether. Trigger File-input with pure HTML/CSS., and it's not hacky at all.

                                                                – Regular Joe
                                                                Oct 11 '17 at 20:27
















                                                              9












                                                              9








                                                              9







                                                              Clean and simple
                                                              JSfiddle



                                                              This will be useful when you want The event to triggered indirectly from a div or a button.



                                                              <img id="image-preview"  style="height:100px; width:100px;"  src="" >

                                                              <input style="display:none" id="input-image-hidden" onchange="document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" type="file" accept="image/jpeg, image/png">

                                                              <button onclick="HandleBrowseClick('input-image-hidden');" >UPLOAD IMAGE</button>


                                                              <script type="text/javascript">
                                                              function HandleBrowseClick(hidden_input_image)
                                                              {
                                                              var fileinputElement = document.getElementById(hidden_input_image);
                                                              fileinputElement.click();
                                                              }
                                                              </script>





                                                              share|improve this answer















                                                              Clean and simple
                                                              JSfiddle



                                                              This will be useful when you want The event to triggered indirectly from a div or a button.



                                                              <img id="image-preview"  style="height:100px; width:100px;"  src="" >

                                                              <input style="display:none" id="input-image-hidden" onchange="document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" type="file" accept="image/jpeg, image/png">

                                                              <button onclick="HandleBrowseClick('input-image-hidden');" >UPLOAD IMAGE</button>


                                                              <script type="text/javascript">
                                                              function HandleBrowseClick(hidden_input_image)
                                                              {
                                                              var fileinputElement = document.getElementById(hidden_input_image);
                                                              fileinputElement.click();
                                                              }
                                                              </script>






                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Dec 13 '17 at 13:39

























                                                              answered Nov 30 '16 at 5:57









                                                              Sivashanmugam KannanSivashanmugam Kannan

                                                              81511326




                                                              81511326













                                                              • Just a note: I can't take credit for this but you can use <label> and avoid javascript for handling the button click altogether. Trigger File-input with pure HTML/CSS., and it's not hacky at all.

                                                                – Regular Joe
                                                                Oct 11 '17 at 20:27





















                                                              • Just a note: I can't take credit for this but you can use <label> and avoid javascript for handling the button click altogether. Trigger File-input with pure HTML/CSS., and it's not hacky at all.

                                                                – Regular Joe
                                                                Oct 11 '17 at 20:27



















                                                              Just a note: I can't take credit for this but you can use <label> and avoid javascript for handling the button click altogether. Trigger File-input with pure HTML/CSS., and it's not hacky at all.

                                                              – Regular Joe
                                                              Oct 11 '17 at 20:27







                                                              Just a note: I can't take credit for this but you can use <label> and avoid javascript for handling the button click altogether. Trigger File-input with pure HTML/CSS., and it's not hacky at all.

                                                              – Regular Joe
                                                              Oct 11 '17 at 20:27













                                                              6














                                                              Example with multiple images using JavaScript (jQuery) and HTML5



                                                              JavaScript (jQuery)



                                                              function readURL(input) {
                                                              for(var i =0; i< input.files.length; i++){
                                                              if (input.files[i]) {
                                                              var reader = new FileReader();

                                                              reader.onload = function (e) {
                                                              var img = $('<img id="dynamic">');
                                                              img.attr('src', e.target.result);
                                                              img.appendTo('#form1');
                                                              }
                                                              reader.readAsDataURL(input.files[i]);
                                                              }
                                                              }
                                                              }

                                                              $("#imgUpload").change(function(){
                                                              readURL(this);
                                                              });
                                                              }


                                                              Markup (HTML)



                                                              <form id="form1" runat="server">
                                                              <input type="file" id="imgUpload" multiple/>
                                                              </form>





                                                              share|improve this answer






























                                                                6














                                                                Example with multiple images using JavaScript (jQuery) and HTML5



                                                                JavaScript (jQuery)



                                                                function readURL(input) {
                                                                for(var i =0; i< input.files.length; i++){
                                                                if (input.files[i]) {
                                                                var reader = new FileReader();

                                                                reader.onload = function (e) {
                                                                var img = $('<img id="dynamic">');
                                                                img.attr('src', e.target.result);
                                                                img.appendTo('#form1');
                                                                }
                                                                reader.readAsDataURL(input.files[i]);
                                                                }
                                                                }
                                                                }

                                                                $("#imgUpload").change(function(){
                                                                readURL(this);
                                                                });
                                                                }


                                                                Markup (HTML)



                                                                <form id="form1" runat="server">
                                                                <input type="file" id="imgUpload" multiple/>
                                                                </form>





                                                                share|improve this answer




























                                                                  6












                                                                  6








                                                                  6







                                                                  Example with multiple images using JavaScript (jQuery) and HTML5



                                                                  JavaScript (jQuery)



                                                                  function readURL(input) {
                                                                  for(var i =0; i< input.files.length; i++){
                                                                  if (input.files[i]) {
                                                                  var reader = new FileReader();

                                                                  reader.onload = function (e) {
                                                                  var img = $('<img id="dynamic">');
                                                                  img.attr('src', e.target.result);
                                                                  img.appendTo('#form1');
                                                                  }
                                                                  reader.readAsDataURL(input.files[i]);
                                                                  }
                                                                  }
                                                                  }

                                                                  $("#imgUpload").change(function(){
                                                                  readURL(this);
                                                                  });
                                                                  }


                                                                  Markup (HTML)



                                                                  <form id="form1" runat="server">
                                                                  <input type="file" id="imgUpload" multiple/>
                                                                  </form>





                                                                  share|improve this answer















                                                                  Example with multiple images using JavaScript (jQuery) and HTML5



                                                                  JavaScript (jQuery)



                                                                  function readURL(input) {
                                                                  for(var i =0; i< input.files.length; i++){
                                                                  if (input.files[i]) {
                                                                  var reader = new FileReader();

                                                                  reader.onload = function (e) {
                                                                  var img = $('<img id="dynamic">');
                                                                  img.attr('src', e.target.result);
                                                                  img.appendTo('#form1');
                                                                  }
                                                                  reader.readAsDataURL(input.files[i]);
                                                                  }
                                                                  }
                                                                  }

                                                                  $("#imgUpload").change(function(){
                                                                  readURL(this);
                                                                  });
                                                                  }


                                                                  Markup (HTML)



                                                                  <form id="form1" runat="server">
                                                                  <input type="file" id="imgUpload" multiple/>
                                                                  </form>






                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited May 2 '17 at 12:59









                                                                  AdamMcquiff

                                                                  1,09211128




                                                                  1,09211128










                                                                  answered Nov 26 '15 at 6:33









                                                                  Ratan PaulRatan Paul

                                                                  283517




                                                                  283517























                                                                      5














                                                                      How about creating a function that loads the file and fires a custom event. Then attach a listener to the input. This way we have more flexibility to use the file, not just for previewing images.



                                                                      /**
                                                                      * @param {domElement} input - The input element
                                                                      * @param {string} typeData - The type of data to be return in the event object.
                                                                      */
                                                                      function loadFileFromInput(input,typeData) {
                                                                      var reader,
                                                                      fileLoadedEvent,
                                                                      files = input.files;

                                                                      if (files && files[0]) {
                                                                      reader = new FileReader();

                                                                      reader.onload = function (e) {
                                                                      fileLoadedEvent = new CustomEvent('fileLoaded',{
                                                                      detail:{
                                                                      data:reader.result,
                                                                      file:files[0]
                                                                      },
                                                                      bubbles:true,
                                                                      cancelable:true
                                                                      });
                                                                      input.dispatchEvent(fileLoadedEvent);
                                                                      }
                                                                      switch(typeData) {
                                                                      case 'arraybuffer':
                                                                      reader.readAsArrayBuffer(files[0]);
                                                                      break;
                                                                      case 'dataurl':
                                                                      reader.readAsDataURL(files[0]);
                                                                      break;
                                                                      case 'binarystring':
                                                                      reader.readAsBinaryString(files[0]);
                                                                      break;
                                                                      case 'text':
                                                                      reader.readAsText(files[0]);
                                                                      break;
                                                                      }
                                                                      }
                                                                      }
                                                                      function fileHandler (e) {
                                                                      var data = e.detail.data,
                                                                      fileInfo = e.detail.file;

                                                                      img.src = data;
                                                                      }
                                                                      var input = document.getElementById('inputId'),
                                                                      img = document.getElementById('imgId');

                                                                      input.onchange = function (e) {
                                                                      loadFileFromInput(e.target,'dataurl');
                                                                      };

                                                                      input.addEventListener('fileLoaded',fileHandler)


                                                                      Probably my code isn't as good as some users but I think you will get the point of it. Here you can see an example






                                                                      share|improve this answer






























                                                                        5














                                                                        How about creating a function that loads the file and fires a custom event. Then attach a listener to the input. This way we have more flexibility to use the file, not just for previewing images.



                                                                        /**
                                                                        * @param {domElement} input - The input element
                                                                        * @param {string} typeData - The type of data to be return in the event object.
                                                                        */
                                                                        function loadFileFromInput(input,typeData) {
                                                                        var reader,
                                                                        fileLoadedEvent,
                                                                        files = input.files;

                                                                        if (files && files[0]) {
                                                                        reader = new FileReader();

                                                                        reader.onload = function (e) {
                                                                        fileLoadedEvent = new CustomEvent('fileLoaded',{
                                                                        detail:{
                                                                        data:reader.result,
                                                                        file:files[0]
                                                                        },
                                                                        bubbles:true,
                                                                        cancelable:true
                                                                        });
                                                                        input.dispatchEvent(fileLoadedEvent);
                                                                        }
                                                                        switch(typeData) {
                                                                        case 'arraybuffer':
                                                                        reader.readAsArrayBuffer(files[0]);
                                                                        break;
                                                                        case 'dataurl':
                                                                        reader.readAsDataURL(files[0]);
                                                                        break;
                                                                        case 'binarystring':
                                                                        reader.readAsBinaryString(files[0]);
                                                                        break;
                                                                        case 'text':
                                                                        reader.readAsText(files[0]);
                                                                        break;
                                                                        }
                                                                        }
                                                                        }
                                                                        function fileHandler (e) {
                                                                        var data = e.detail.data,
                                                                        fileInfo = e.detail.file;

                                                                        img.src = data;
                                                                        }
                                                                        var input = document.getElementById('inputId'),
                                                                        img = document.getElementById('imgId');

                                                                        input.onchange = function (e) {
                                                                        loadFileFromInput(e.target,'dataurl');
                                                                        };

                                                                        input.addEventListener('fileLoaded',fileHandler)


                                                                        Probably my code isn't as good as some users but I think you will get the point of it. Here you can see an example






                                                                        share|improve this answer




























                                                                          5












                                                                          5








                                                                          5







                                                                          How about creating a function that loads the file and fires a custom event. Then attach a listener to the input. This way we have more flexibility to use the file, not just for previewing images.



                                                                          /**
                                                                          * @param {domElement} input - The input element
                                                                          * @param {string} typeData - The type of data to be return in the event object.
                                                                          */
                                                                          function loadFileFromInput(input,typeData) {
                                                                          var reader,
                                                                          fileLoadedEvent,
                                                                          files = input.files;

                                                                          if (files && files[0]) {
                                                                          reader = new FileReader();

                                                                          reader.onload = function (e) {
                                                                          fileLoadedEvent = new CustomEvent('fileLoaded',{
                                                                          detail:{
                                                                          data:reader.result,
                                                                          file:files[0]
                                                                          },
                                                                          bubbles:true,
                                                                          cancelable:true
                                                                          });
                                                                          input.dispatchEvent(fileLoadedEvent);
                                                                          }
                                                                          switch(typeData) {
                                                                          case 'arraybuffer':
                                                                          reader.readAsArrayBuffer(files[0]);
                                                                          break;
                                                                          case 'dataurl':
                                                                          reader.readAsDataURL(files[0]);
                                                                          break;
                                                                          case 'binarystring':
                                                                          reader.readAsBinaryString(files[0]);
                                                                          break;
                                                                          case 'text':
                                                                          reader.readAsText(files[0]);
                                                                          break;
                                                                          }
                                                                          }
                                                                          }
                                                                          function fileHandler (e) {
                                                                          var data = e.detail.data,
                                                                          fileInfo = e.detail.file;

                                                                          img.src = data;
                                                                          }
                                                                          var input = document.getElementById('inputId'),
                                                                          img = document.getElementById('imgId');

                                                                          input.onchange = function (e) {
                                                                          loadFileFromInput(e.target,'dataurl');
                                                                          };

                                                                          input.addEventListener('fileLoaded',fileHandler)


                                                                          Probably my code isn't as good as some users but I think you will get the point of it. Here you can see an example






                                                                          share|improve this answer















                                                                          How about creating a function that loads the file and fires a custom event. Then attach a listener to the input. This way we have more flexibility to use the file, not just for previewing images.



                                                                          /**
                                                                          * @param {domElement} input - The input element
                                                                          * @param {string} typeData - The type of data to be return in the event object.
                                                                          */
                                                                          function loadFileFromInput(input,typeData) {
                                                                          var reader,
                                                                          fileLoadedEvent,
                                                                          files = input.files;

                                                                          if (files && files[0]) {
                                                                          reader = new FileReader();

                                                                          reader.onload = function (e) {
                                                                          fileLoadedEvent = new CustomEvent('fileLoaded',{
                                                                          detail:{
                                                                          data:reader.result,
                                                                          file:files[0]
                                                                          },
                                                                          bubbles:true,
                                                                          cancelable:true
                                                                          });
                                                                          input.dispatchEvent(fileLoadedEvent);
                                                                          }
                                                                          switch(typeData) {
                                                                          case 'arraybuffer':
                                                                          reader.readAsArrayBuffer(files[0]);
                                                                          break;
                                                                          case 'dataurl':
                                                                          reader.readAsDataURL(files[0]);
                                                                          break;
                                                                          case 'binarystring':
                                                                          reader.readAsBinaryString(files[0]);
                                                                          break;
                                                                          case 'text':
                                                                          reader.readAsText(files[0]);
                                                                          break;
                                                                          }
                                                                          }
                                                                          }
                                                                          function fileHandler (e) {
                                                                          var data = e.detail.data,
                                                                          fileInfo = e.detail.file;

                                                                          img.src = data;
                                                                          }
                                                                          var input = document.getElementById('inputId'),
                                                                          img = document.getElementById('imgId');

                                                                          input.onchange = function (e) {
                                                                          loadFileFromInput(e.target,'dataurl');
                                                                          };

                                                                          input.addEventListener('fileLoaded',fileHandler)


                                                                          Probably my code isn't as good as some users but I think you will get the point of it. Here you can see an example







                                                                          share|improve this answer














                                                                          share|improve this answer



                                                                          share|improve this answer








                                                                          edited Mar 21 '14 at 13:28


























                                                                          community wiki





                                                                          2 revs
                                                                          ajorquera
























                                                                              3














                                                                              Following is the working code.



                                                                              <input type='file' onchange="readURL(this);" /> 
                                                                              <img id="ShowImage" src="#" />


                                                                              Javascript:



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

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

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





                                                                              share|improve this answer




























                                                                                3














                                                                                Following is the working code.



                                                                                <input type='file' onchange="readURL(this);" /> 
                                                                                <img id="ShowImage" src="#" />


                                                                                Javascript:



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

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

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





                                                                                share|improve this answer


























                                                                                  3












                                                                                  3








                                                                                  3







                                                                                  Following is the working code.



                                                                                  <input type='file' onchange="readURL(this);" /> 
                                                                                  <img id="ShowImage" src="#" />


                                                                                  Javascript:



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

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

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





                                                                                  share|improve this answer













                                                                                  Following is the working code.



                                                                                  <input type='file' onchange="readURL(this);" /> 
                                                                                  <img id="ShowImage" src="#" />


                                                                                  Javascript:



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

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

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






                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Jul 29 '16 at 18:41









                                                                                  Muhammad AwaisMuhammad Awais

                                                                                  1,87112420




                                                                                  1,87112420























                                                                                      2














                                                                                      What about this solution?



                                                                                      Just add the data attribute "data-type=editable" to an image tag like this:



                                                                                      <img data-type="editable" id="companyLogo" src="http://www.coventrywebgraphicdesign.co.uk/wp-content/uploads/logo-here.jpg" height="300px" width="300px" />


                                                                                      And the script to your project off course...



                                                                                      function init() {
                                                                                      $("img[data-type=editable]").each(function (i, e) {
                                                                                      var _inputFile = $('<input/>')
                                                                                      .attr('type', 'file')
                                                                                      .attr('hidden', 'hidden')
                                                                                      .attr('onchange', 'readImage()')
                                                                                      .attr('data-image-placeholder', e.id);

                                                                                      $(e.parentElement).append(_inputFile);

                                                                                      $(e).on("click", _inputFile, triggerClick);
                                                                                      });
                                                                                      }

                                                                                      function triggerClick(e) {
                                                                                      e.data.click();
                                                                                      }

                                                                                      Element.prototype.readImage = function () {
                                                                                      var _inputFile = this;
                                                                                      if (_inputFile && _inputFile.files && _inputFile.files[0]) {
                                                                                      var _fileReader = new FileReader();
                                                                                      _fileReader.onload = function (e) {
                                                                                      var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;
                                                                                      var _img = $("#" + _imagePlaceholder);
                                                                                      _img.attr("src", e.target.result);
                                                                                      };
                                                                                      _fileReader.readAsDataURL(_inputFile.files[0]);
                                                                                      }
                                                                                      };

                                                                                      //
                                                                                      // IIFE - Immediately Invoked Function Expression
                                                                                      // https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
                                                                                      (

                                                                                      function (yourcode) {
                                                                                      "use strict";
                                                                                      // The global jQuery object is passed as a parameter
                                                                                      yourcode(window.jQuery, window, document);
                                                                                      }(

                                                                                      function ($, window, document) {
                                                                                      "use strict";
                                                                                      // The $ is now locally scoped
                                                                                      $(function () {
                                                                                      // The DOM is ready!
                                                                                      init();
                                                                                      });

                                                                                      // The rest of your code goes here!
                                                                                      }));


                                                                                      See demo at JSFiddle






                                                                                      share|improve this answer




























                                                                                        2














                                                                                        What about this solution?



                                                                                        Just add the data attribute "data-type=editable" to an image tag like this:



                                                                                        <img data-type="editable" id="companyLogo" src="http://www.coventrywebgraphicdesign.co.uk/wp-content/uploads/logo-here.jpg" height="300px" width="300px" />


                                                                                        And the script to your project off course...



                                                                                        function init() {
                                                                                        $("img[data-type=editable]").each(function (i, e) {
                                                                                        var _inputFile = $('<input/>')
                                                                                        .attr('type', 'file')
                                                                                        .attr('hidden', 'hidden')
                                                                                        .attr('onchange', 'readImage()')
                                                                                        .attr('data-image-placeholder', e.id);

                                                                                        $(e.parentElement).append(_inputFile);

                                                                                        $(e).on("click", _inputFile, triggerClick);
                                                                                        });
                                                                                        }

                                                                                        function triggerClick(e) {
                                                                                        e.data.click();
                                                                                        }

                                                                                        Element.prototype.readImage = function () {
                                                                                        var _inputFile = this;
                                                                                        if (_inputFile && _inputFile.files && _inputFile.files[0]) {
                                                                                        var _fileReader = new FileReader();
                                                                                        _fileReader.onload = function (e) {
                                                                                        var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;
                                                                                        var _img = $("#" + _imagePlaceholder);
                                                                                        _img.attr("src", e.target.result);
                                                                                        };
                                                                                        _fileReader.readAsDataURL(_inputFile.files[0]);
                                                                                        }
                                                                                        };

                                                                                        //
                                                                                        // IIFE - Immediately Invoked Function Expression
                                                                                        // https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
                                                                                        (

                                                                                        function (yourcode) {
                                                                                        "use strict";
                                                                                        // The global jQuery object is passed as a parameter
                                                                                        yourcode(window.jQuery, window, document);
                                                                                        }(

                                                                                        function ($, window, document) {
                                                                                        "use strict";
                                                                                        // The $ is now locally scoped
                                                                                        $(function () {
                                                                                        // The DOM is ready!
                                                                                        init();
                                                                                        });

                                                                                        // The rest of your code goes here!
                                                                                        }));


                                                                                        See demo at JSFiddle






                                                                                        share|improve this answer


























                                                                                          2












                                                                                          2








                                                                                          2







                                                                                          What about this solution?



                                                                                          Just add the data attribute "data-type=editable" to an image tag like this:



                                                                                          <img data-type="editable" id="companyLogo" src="http://www.coventrywebgraphicdesign.co.uk/wp-content/uploads/logo-here.jpg" height="300px" width="300px" />


                                                                                          And the script to your project off course...



                                                                                          function init() {
                                                                                          $("img[data-type=editable]").each(function (i, e) {
                                                                                          var _inputFile = $('<input/>')
                                                                                          .attr('type', 'file')
                                                                                          .attr('hidden', 'hidden')
                                                                                          .attr('onchange', 'readImage()')
                                                                                          .attr('data-image-placeholder', e.id);

                                                                                          $(e.parentElement).append(_inputFile);

                                                                                          $(e).on("click", _inputFile, triggerClick);
                                                                                          });
                                                                                          }

                                                                                          function triggerClick(e) {
                                                                                          e.data.click();
                                                                                          }

                                                                                          Element.prototype.readImage = function () {
                                                                                          var _inputFile = this;
                                                                                          if (_inputFile && _inputFile.files && _inputFile.files[0]) {
                                                                                          var _fileReader = new FileReader();
                                                                                          _fileReader.onload = function (e) {
                                                                                          var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;
                                                                                          var _img = $("#" + _imagePlaceholder);
                                                                                          _img.attr("src", e.target.result);
                                                                                          };
                                                                                          _fileReader.readAsDataURL(_inputFile.files[0]);
                                                                                          }
                                                                                          };

                                                                                          //
                                                                                          // IIFE - Immediately Invoked Function Expression
                                                                                          // https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
                                                                                          (

                                                                                          function (yourcode) {
                                                                                          "use strict";
                                                                                          // The global jQuery object is passed as a parameter
                                                                                          yourcode(window.jQuery, window, document);
                                                                                          }(

                                                                                          function ($, window, document) {
                                                                                          "use strict";
                                                                                          // The $ is now locally scoped
                                                                                          $(function () {
                                                                                          // The DOM is ready!
                                                                                          init();
                                                                                          });

                                                                                          // The rest of your code goes here!
                                                                                          }));


                                                                                          See demo at JSFiddle






                                                                                          share|improve this answer













                                                                                          What about this solution?



                                                                                          Just add the data attribute "data-type=editable" to an image tag like this:



                                                                                          <img data-type="editable" id="companyLogo" src="http://www.coventrywebgraphicdesign.co.uk/wp-content/uploads/logo-here.jpg" height="300px" width="300px" />


                                                                                          And the script to your project off course...



                                                                                          function init() {
                                                                                          $("img[data-type=editable]").each(function (i, e) {
                                                                                          var _inputFile = $('<input/>')
                                                                                          .attr('type', 'file')
                                                                                          .attr('hidden', 'hidden')
                                                                                          .attr('onchange', 'readImage()')
                                                                                          .attr('data-image-placeholder', e.id);

                                                                                          $(e.parentElement).append(_inputFile);

                                                                                          $(e).on("click", _inputFile, triggerClick);
                                                                                          });
                                                                                          }

                                                                                          function triggerClick(e) {
                                                                                          e.data.click();
                                                                                          }

                                                                                          Element.prototype.readImage = function () {
                                                                                          var _inputFile = this;
                                                                                          if (_inputFile && _inputFile.files && _inputFile.files[0]) {
                                                                                          var _fileReader = new FileReader();
                                                                                          _fileReader.onload = function (e) {
                                                                                          var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;
                                                                                          var _img = $("#" + _imagePlaceholder);
                                                                                          _img.attr("src", e.target.result);
                                                                                          };
                                                                                          _fileReader.readAsDataURL(_inputFile.files[0]);
                                                                                          }
                                                                                          };

                                                                                          //
                                                                                          // IIFE - Immediately Invoked Function Expression
                                                                                          // https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
                                                                                          (

                                                                                          function (yourcode) {
                                                                                          "use strict";
                                                                                          // The global jQuery object is passed as a parameter
                                                                                          yourcode(window.jQuery, window, document);
                                                                                          }(

                                                                                          function ($, window, document) {
                                                                                          "use strict";
                                                                                          // The $ is now locally scoped
                                                                                          $(function () {
                                                                                          // The DOM is ready!
                                                                                          init();
                                                                                          });

                                                                                          // The rest of your code goes here!
                                                                                          }));


                                                                                          See demo at JSFiddle







                                                                                          share|improve this answer












                                                                                          share|improve this answer



                                                                                          share|improve this answer










                                                                                          answered Jan 6 '15 at 16:19









                                                                                          Rodolpho BrockRodolpho Brock

                                                                                          6,23821824




                                                                                          6,23821824























                                                                                              1














                                                                                              I have made a plugin which can generate the preview effect in IE 7+ thanks to the internet, but has few limitations. I put it into a github page so that its easier to get it






                                                                                              $(function () {
                                                                                              $("input[name=file1]").previewimage({
                                                                                              div: ".preview",
                                                                                              imgwidth: 180,
                                                                                              imgheight: 120
                                                                                              });
                                                                                              $("input[name=file2]").previewimage({
                                                                                              div: ".preview2",
                                                                                              imgwidth: 90,
                                                                                              imgheight: 90
                                                                                              });
                                                                                              });

                                                                                              .preview > div {
                                                                                              display: inline-block;
                                                                                              text-align:center;
                                                                                              }

                                                                                              .preview2 > div {
                                                                                              display: inline-block;
                                                                                              text-align:center;
                                                                                              }

                                                                                              <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
                                                                                              <script src="https://rawgit.com/andrewng330/PreviewImage/master/preview.image.min.js"></script>
                                                                                              Preview
                                                                                              <div class="preview"></div>
                                                                                              Preview2
                                                                                              <div class="preview2"></div>

                                                                                              <form action="#" method="POST" enctype="multipart/form-data">
                                                                                              <input type="file" name="file1">
                                                                                              <input type="file" name="file2">
                                                                                              <input type="submit">
                                                                                              </form>








                                                                                              share|improve this answer






























                                                                                                1














                                                                                                I have made a plugin which can generate the preview effect in IE 7+ thanks to the internet, but has few limitations. I put it into a github page so that its easier to get it






                                                                                                $(function () {
                                                                                                $("input[name=file1]").previewimage({
                                                                                                div: ".preview",
                                                                                                imgwidth: 180,
                                                                                                imgheight: 120
                                                                                                });
                                                                                                $("input[name=file2]").previewimage({
                                                                                                div: ".preview2",
                                                                                                imgwidth: 90,
                                                                                                imgheight: 90
                                                                                                });
                                                                                                });

                                                                                                .preview > div {
                                                                                                display: inline-block;
                                                                                                text-align:center;
                                                                                                }

                                                                                                .preview2 > div {
                                                                                                display: inline-block;
                                                                                                text-align:center;
                                                                                                }

                                                                                                <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
                                                                                                <script src="https://rawgit.com/andrewng330/PreviewImage/master/preview.image.min.js"></script>
                                                                                                Preview
                                                                                                <div class="preview"></div>
                                                                                                Preview2
                                                                                                <div class="preview2"></div>

                                                                                                <form action="#" method="POST" enctype="multipart/form-data">
                                                                                                <input type="file" name="file1">
                                                                                                <input type="file" name="file2">
                                                                                                <input type="submit">
                                                                                                </form>








                                                                                                share|improve this answer




























                                                                                                  1












                                                                                                  1








                                                                                                  1







                                                                                                  I have made a plugin which can generate the preview effect in IE 7+ thanks to the internet, but has few limitations. I put it into a github page so that its easier to get it






                                                                                                  $(function () {
                                                                                                  $("input[name=file1]").previewimage({
                                                                                                  div: ".preview",
                                                                                                  imgwidth: 180,
                                                                                                  imgheight: 120
                                                                                                  });
                                                                                                  $("input[name=file2]").previewimage({
                                                                                                  div: ".preview2",
                                                                                                  imgwidth: 90,
                                                                                                  imgheight: 90
                                                                                                  });
                                                                                                  });

                                                                                                  .preview > div {
                                                                                                  display: inline-block;
                                                                                                  text-align:center;
                                                                                                  }

                                                                                                  .preview2 > div {
                                                                                                  display: inline-block;
                                                                                                  text-align:center;
                                                                                                  }

                                                                                                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
                                                                                                  <script src="https://rawgit.com/andrewng330/PreviewImage/master/preview.image.min.js"></script>
                                                                                                  Preview
                                                                                                  <div class="preview"></div>
                                                                                                  Preview2
                                                                                                  <div class="preview2"></div>

                                                                                                  <form action="#" method="POST" enctype="multipart/form-data">
                                                                                                  <input type="file" name="file1">
                                                                                                  <input type="file" name="file2">
                                                                                                  <input type="submit">
                                                                                                  </form>








                                                                                                  share|improve this answer















                                                                                                  I have made a plugin which can generate the preview effect in IE 7+ thanks to the internet, but has few limitations. I put it into a github page so that its easier to get it






                                                                                                  $(function () {
                                                                                                  $("input[name=file1]").previewimage({
                                                                                                  div: ".preview",
                                                                                                  imgwidth: 180,
                                                                                                  imgheight: 120
                                                                                                  });
                                                                                                  $("input[name=file2]").previewimage({
                                                                                                  div: ".preview2",
                                                                                                  imgwidth: 90,
                                                                                                  imgheight: 90
                                                                                                  });
                                                                                                  });

                                                                                                  .preview > div {
                                                                                                  display: inline-block;
                                                                                                  text-align:center;
                                                                                                  }

                                                                                                  .preview2 > div {
                                                                                                  display: inline-block;
                                                                                                  text-align:center;
                                                                                                  }

                                                                                                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
                                                                                                  <script src="https://rawgit.com/andrewng330/PreviewImage/master/preview.image.min.js"></script>
                                                                                                  Preview
                                                                                                  <div class="preview"></div>
                                                                                                  Preview2
                                                                                                  <div class="preview2"></div>

                                                                                                  <form action="#" method="POST" enctype="multipart/form-data">
                                                                                                  <input type="file" name="file1">
                                                                                                  <input type="file" name="file2">
                                                                                                  <input type="submit">
                                                                                                  </form>








                                                                                                  $(function () {
                                                                                                  $("input[name=file1]").previewimage({
                                                                                                  div: ".preview",
                                                                                                  imgwidth: 180,
                                                                                                  imgheight: 120
                                                                                                  });
                                                                                                  $("input[name=file2]").previewimage({
                                                                                                  div: ".preview2",
                                                                                                  imgwidth: 90,
                                                                                                  imgheight: 90
                                                                                                  });
                                                                                                  });

                                                                                                  .preview > div {
                                                                                                  display: inline-block;
                                                                                                  text-align:center;
                                                                                                  }

                                                                                                  .preview2 > div {
                                                                                                  display: inline-block;
                                                                                                  text-align:center;
                                                                                                  }

                                                                                                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
                                                                                                  <script src="https://rawgit.com/andrewng330/PreviewImage/master/preview.image.min.js"></script>
                                                                                                  Preview
                                                                                                  <div class="preview"></div>
                                                                                                  Preview2
                                                                                                  <div class="preview2"></div>

                                                                                                  <form action="#" method="POST" enctype="multipart/form-data">
                                                                                                  <input type="file" name="file1">
                                                                                                  <input type="file" name="file2">
                                                                                                  <input type="submit">
                                                                                                  </form>





                                                                                                  $(function () {
                                                                                                  $("input[name=file1]").previewimage({
                                                                                                  div: ".preview",
                                                                                                  imgwidth: 180,
                                                                                                  imgheight: 120
                                                                                                  });
                                                                                                  $("input[name=file2]").previewimage({
                                                                                                  div: ".preview2",
                                                                                                  imgwidth: 90,
                                                                                                  imgheight: 90
                                                                                                  });
                                                                                                  });

                                                                                                  .preview > div {
                                                                                                  display: inline-block;
                                                                                                  text-align:center;
                                                                                                  }

                                                                                                  .preview2 > div {
                                                                                                  display: inline-block;
                                                                                                  text-align:center;
                                                                                                  }

                                                                                                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
                                                                                                  <script src="https://rawgit.com/andrewng330/PreviewImage/master/preview.image.min.js"></script>
                                                                                                  Preview
                                                                                                  <div class="preview"></div>
                                                                                                  Preview2
                                                                                                  <div class="preview2"></div>

                                                                                                  <form action="#" method="POST" enctype="multipart/form-data">
                                                                                                  <input type="file" name="file1">
                                                                                                  <input type="file" name="file2">
                                                                                                  <input type="submit">
                                                                                                  </form>






                                                                                                  share|improve this answer














                                                                                                  share|improve this answer



                                                                                                  share|improve this answer








                                                                                                  edited Jul 27 '15 at 7:23

























                                                                                                  answered Jul 27 '15 at 6:01









                                                                                                  AndrewAndrew

                                                                                                  1,57631130




                                                                                                  1,57631130























                                                                                                      1














                                                                                                      For Multiple image upload (Modification to the @IvanBaev's Solution)



                                                                                                      function readURL(input) {
                                                                                                      if (input.files && input.files[0]) {
                                                                                                      var i;
                                                                                                      for (i = 0; i < input.files.length; ++i) {
                                                                                                      var reader = new FileReader();
                                                                                                      reader.onload = function (e) {
                                                                                                      $('#form1').append('<img src="'+e.target.result+'">');
                                                                                                      }
                                                                                                      reader.readAsDataURL(input.files[i]);
                                                                                                      }
                                                                                                      }
                                                                                                      }


                                                                                                      http://jsfiddle.net/LvsYc/12330/



                                                                                                      Hope this helps someone.






                                                                                                      share|improve this answer




























                                                                                                        1














                                                                                                        For Multiple image upload (Modification to the @IvanBaev's Solution)



                                                                                                        function readURL(input) {
                                                                                                        if (input.files && input.files[0]) {
                                                                                                        var i;
                                                                                                        for (i = 0; i < input.files.length; ++i) {
                                                                                                        var reader = new FileReader();
                                                                                                        reader.onload = function (e) {
                                                                                                        $('#form1').append('<img src="'+e.target.result+'">');
                                                                                                        }
                                                                                                        reader.readAsDataURL(input.files[i]);
                                                                                                        }
                                                                                                        }
                                                                                                        }


                                                                                                        http://jsfiddle.net/LvsYc/12330/



                                                                                                        Hope this helps someone.






                                                                                                        share|improve this answer


























                                                                                                          1












                                                                                                          1








                                                                                                          1







                                                                                                          For Multiple image upload (Modification to the @IvanBaev's Solution)



                                                                                                          function readURL(input) {
                                                                                                          if (input.files && input.files[0]) {
                                                                                                          var i;
                                                                                                          for (i = 0; i < input.files.length; ++i) {
                                                                                                          var reader = new FileReader();
                                                                                                          reader.onload = function (e) {
                                                                                                          $('#form1').append('<img src="'+e.target.result+'">');
                                                                                                          }
                                                                                                          reader.readAsDataURL(input.files[i]);
                                                                                                          }
                                                                                                          }
                                                                                                          }


                                                                                                          http://jsfiddle.net/LvsYc/12330/



                                                                                                          Hope this helps someone.






                                                                                                          share|improve this answer













                                                                                                          For Multiple image upload (Modification to the @IvanBaev's Solution)



                                                                                                          function readURL(input) {
                                                                                                          if (input.files && input.files[0]) {
                                                                                                          var i;
                                                                                                          for (i = 0; i < input.files.length; ++i) {
                                                                                                          var reader = new FileReader();
                                                                                                          reader.onload = function (e) {
                                                                                                          $('#form1').append('<img src="'+e.target.result+'">');
                                                                                                          }
                                                                                                          reader.readAsDataURL(input.files[i]);
                                                                                                          }
                                                                                                          }
                                                                                                          }


                                                                                                          http://jsfiddle.net/LvsYc/12330/



                                                                                                          Hope this helps someone.







                                                                                                          share|improve this answer












                                                                                                          share|improve this answer



                                                                                                          share|improve this answer










                                                                                                          answered Dec 16 '17 at 14:46









                                                                                                          Keyur KKeyur K

                                                                                                          5351227




                                                                                                          5351227























                                                                                                              0














                                                                                                              It's my code.Support IE[6-9]、chrome 17+、firefox、Opera 11+、Maxthon3



                                                                                                              HTML



                                                                                                              <input type="file"  id="netBarBig"  onchange="changeFile(this)"  />
                                                                                                              <img src="" id="imagePreview" style="width:120px;height:80px;" alt=""/>


                                                                                                              javascript:






                                                                                                              <script>

                                                                                                              function previewImage(fileObj, imgPreviewId) {
                                                                                                              var allowExtention = ".jpg,.bmp,.gif,.png"; //allowed to upload file type
                                                                                                              document.getElementById("hfAllowPicSuffix").value;
                                                                                                              var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
                                                                                                              var browserVersion = window.navigator.userAgent.toUpperCase();
                                                                                                              if (allowExtention.indexOf(extention) > -1) {
                                                                                                              if (fileObj.files) {
                                                                                                              if (window.FileReader) {
                                                                                                              var reader = new FileReader();
                                                                                                              reader.onload = function (e) {
                                                                                                              document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
                                                                                                              };
                                                                                                              reader.readAsDataURL(fileObj.files[0]);
                                                                                                              } else if (browserVersion.indexOf("SAFARI") > -1) {
                                                                                                              alert("don't support Safari6.0 below broswer");
                                                                                                              }
                                                                                                              } else if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                              if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
                                                                                                              document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                              } else {//ie[7-9]
                                                                                                              fileObj.select();
                                                                                                              fileObj.blur();
                                                                                                              var newPreview = document.getElementById(imgPreviewId);

                                                                                                              newPreview.style.border = "solid 1px #eeeeee";
                                                                                                              newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
                                                                                                              newPreview.style.display = "block";

                                                                                                              }
                                                                                                              } else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
                                                                                                              var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox/([d.]+)/)[1]);
                                                                                                              if (firefoxVersion < 7) {//firefox7 below
                                                                                                              document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
                                                                                                              } else {//firefox7.0+ 
                                                                                                              document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
                                                                                                              }
                                                                                                              } else {
                                                                                                              document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                              }
                                                                                                              } else {
                                                                                                              alert("only support" + allowExtention + "suffix");
                                                                                                              fileObj.value = ""; //clear Selected file
                                                                                                              if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                              fileObj.select();
                                                                                                              document.selection.clear();
                                                                                                              }

                                                                                                              }
                                                                                                              }
                                                                                                              function changeFile(elem) {
                                                                                                              //file object , preview img tag id
                                                                                                              previewImage(elem,'imagePreview')
                                                                                                              }

                                                                                                              </script>








                                                                                                              share|improve this answer




























                                                                                                                0














                                                                                                                It's my code.Support IE[6-9]、chrome 17+、firefox、Opera 11+、Maxthon3



                                                                                                                HTML



                                                                                                                <input type="file"  id="netBarBig"  onchange="changeFile(this)"  />
                                                                                                                <img src="" id="imagePreview" style="width:120px;height:80px;" alt=""/>


                                                                                                                javascript:






                                                                                                                <script>

                                                                                                                function previewImage(fileObj, imgPreviewId) {
                                                                                                                var allowExtention = ".jpg,.bmp,.gif,.png"; //allowed to upload file type
                                                                                                                document.getElementById("hfAllowPicSuffix").value;
                                                                                                                var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
                                                                                                                var browserVersion = window.navigator.userAgent.toUpperCase();
                                                                                                                if (allowExtention.indexOf(extention) > -1) {
                                                                                                                if (fileObj.files) {
                                                                                                                if (window.FileReader) {
                                                                                                                var reader = new FileReader();
                                                                                                                reader.onload = function (e) {
                                                                                                                document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
                                                                                                                };
                                                                                                                reader.readAsDataURL(fileObj.files[0]);
                                                                                                                } else if (browserVersion.indexOf("SAFARI") > -1) {
                                                                                                                alert("don't support Safari6.0 below broswer");
                                                                                                                }
                                                                                                                } else if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                                if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
                                                                                                                document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                                } else {//ie[7-9]
                                                                                                                fileObj.select();
                                                                                                                fileObj.blur();
                                                                                                                var newPreview = document.getElementById(imgPreviewId);

                                                                                                                newPreview.style.border = "solid 1px #eeeeee";
                                                                                                                newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
                                                                                                                newPreview.style.display = "block";

                                                                                                                }
                                                                                                                } else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
                                                                                                                var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox/([d.]+)/)[1]);
                                                                                                                if (firefoxVersion < 7) {//firefox7 below
                                                                                                                document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
                                                                                                                } else {//firefox7.0+ 
                                                                                                                document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
                                                                                                                }
                                                                                                                } else {
                                                                                                                document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                                }
                                                                                                                } else {
                                                                                                                alert("only support" + allowExtention + "suffix");
                                                                                                                fileObj.value = ""; //clear Selected file
                                                                                                                if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                                fileObj.select();
                                                                                                                document.selection.clear();
                                                                                                                }

                                                                                                                }
                                                                                                                }
                                                                                                                function changeFile(elem) {
                                                                                                                //file object , preview img tag id
                                                                                                                previewImage(elem,'imagePreview')
                                                                                                                }

                                                                                                                </script>








                                                                                                                share|improve this answer


























                                                                                                                  0












                                                                                                                  0








                                                                                                                  0







                                                                                                                  It's my code.Support IE[6-9]、chrome 17+、firefox、Opera 11+、Maxthon3



                                                                                                                  HTML



                                                                                                                  <input type="file"  id="netBarBig"  onchange="changeFile(this)"  />
                                                                                                                  <img src="" id="imagePreview" style="width:120px;height:80px;" alt=""/>


                                                                                                                  javascript:






                                                                                                                  <script>

                                                                                                                  function previewImage(fileObj, imgPreviewId) {
                                                                                                                  var allowExtention = ".jpg,.bmp,.gif,.png"; //allowed to upload file type
                                                                                                                  document.getElementById("hfAllowPicSuffix").value;
                                                                                                                  var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
                                                                                                                  var browserVersion = window.navigator.userAgent.toUpperCase();
                                                                                                                  if (allowExtention.indexOf(extention) > -1) {
                                                                                                                  if (fileObj.files) {
                                                                                                                  if (window.FileReader) {
                                                                                                                  var reader = new FileReader();
                                                                                                                  reader.onload = function (e) {
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
                                                                                                                  };
                                                                                                                  reader.readAsDataURL(fileObj.files[0]);
                                                                                                                  } else if (browserVersion.indexOf("SAFARI") > -1) {
                                                                                                                  alert("don't support Safari6.0 below broswer");
                                                                                                                  }
                                                                                                                  } else if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                                  if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                                  } else {//ie[7-9]
                                                                                                                  fileObj.select();
                                                                                                                  fileObj.blur();
                                                                                                                  var newPreview = document.getElementById(imgPreviewId);

                                                                                                                  newPreview.style.border = "solid 1px #eeeeee";
                                                                                                                  newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
                                                                                                                  newPreview.style.display = "block";

                                                                                                                  }
                                                                                                                  } else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
                                                                                                                  var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox/([d.]+)/)[1]);
                                                                                                                  if (firefoxVersion < 7) {//firefox7 below
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
                                                                                                                  } else {//firefox7.0+ 
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
                                                                                                                  }
                                                                                                                  } else {
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                                  }
                                                                                                                  } else {
                                                                                                                  alert("only support" + allowExtention + "suffix");
                                                                                                                  fileObj.value = ""; //clear Selected file
                                                                                                                  if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                                  fileObj.select();
                                                                                                                  document.selection.clear();
                                                                                                                  }

                                                                                                                  }
                                                                                                                  }
                                                                                                                  function changeFile(elem) {
                                                                                                                  //file object , preview img tag id
                                                                                                                  previewImage(elem,'imagePreview')
                                                                                                                  }

                                                                                                                  </script>








                                                                                                                  share|improve this answer













                                                                                                                  It's my code.Support IE[6-9]、chrome 17+、firefox、Opera 11+、Maxthon3



                                                                                                                  HTML



                                                                                                                  <input type="file"  id="netBarBig"  onchange="changeFile(this)"  />
                                                                                                                  <img src="" id="imagePreview" style="width:120px;height:80px;" alt=""/>


                                                                                                                  javascript:






                                                                                                                  <script>

                                                                                                                  function previewImage(fileObj, imgPreviewId) {
                                                                                                                  var allowExtention = ".jpg,.bmp,.gif,.png"; //allowed to upload file type
                                                                                                                  document.getElementById("hfAllowPicSuffix").value;
                                                                                                                  var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
                                                                                                                  var browserVersion = window.navigator.userAgent.toUpperCase();
                                                                                                                  if (allowExtention.indexOf(extention) > -1) {
                                                                                                                  if (fileObj.files) {
                                                                                                                  if (window.FileReader) {
                                                                                                                  var reader = new FileReader();
                                                                                                                  reader.onload = function (e) {
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
                                                                                                                  };
                                                                                                                  reader.readAsDataURL(fileObj.files[0]);
                                                                                                                  } else if (browserVersion.indexOf("SAFARI") > -1) {
                                                                                                                  alert("don't support Safari6.0 below broswer");
                                                                                                                  }
                                                                                                                  } else if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                                  if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                                  } else {//ie[7-9]
                                                                                                                  fileObj.select();
                                                                                                                  fileObj.blur();
                                                                                                                  var newPreview = document.getElementById(imgPreviewId);

                                                                                                                  newPreview.style.border = "solid 1px #eeeeee";
                                                                                                                  newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
                                                                                                                  newPreview.style.display = "block";

                                                                                                                  }
                                                                                                                  } else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
                                                                                                                  var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox/([d.]+)/)[1]);
                                                                                                                  if (firefoxVersion < 7) {//firefox7 below
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
                                                                                                                  } else {//firefox7.0+ 
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
                                                                                                                  }
                                                                                                                  } else {
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                                  }
                                                                                                                  } else {
                                                                                                                  alert("only support" + allowExtention + "suffix");
                                                                                                                  fileObj.value = ""; //clear Selected file
                                                                                                                  if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                                  fileObj.select();
                                                                                                                  document.selection.clear();
                                                                                                                  }

                                                                                                                  }
                                                                                                                  }
                                                                                                                  function changeFile(elem) {
                                                                                                                  //file object , preview img tag id
                                                                                                                  previewImage(elem,'imagePreview')
                                                                                                                  }

                                                                                                                  </script>








                                                                                                                  <script>

                                                                                                                  function previewImage(fileObj, imgPreviewId) {
                                                                                                                  var allowExtention = ".jpg,.bmp,.gif,.png"; //allowed to upload file type
                                                                                                                  document.getElementById("hfAllowPicSuffix").value;
                                                                                                                  var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
                                                                                                                  var browserVersion = window.navigator.userAgent.toUpperCase();
                                                                                                                  if (allowExtention.indexOf(extention) > -1) {
                                                                                                                  if (fileObj.files) {
                                                                                                                  if (window.FileReader) {
                                                                                                                  var reader = new FileReader();
                                                                                                                  reader.onload = function (e) {
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
                                                                                                                  };
                                                                                                                  reader.readAsDataURL(fileObj.files[0]);
                                                                                                                  } else if (browserVersion.indexOf("SAFARI") > -1) {
                                                                                                                  alert("don't support Safari6.0 below broswer");
                                                                                                                  }
                                                                                                                  } else if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                                  if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                                  } else {//ie[7-9]
                                                                                                                  fileObj.select();
                                                                                                                  fileObj.blur();
                                                                                                                  var newPreview = document.getElementById(imgPreviewId);

                                                                                                                  newPreview.style.border = "solid 1px #eeeeee";
                                                                                                                  newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
                                                                                                                  newPreview.style.display = "block";

                                                                                                                  }
                                                                                                                  } else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
                                                                                                                  var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox/([d.]+)/)[1]);
                                                                                                                  if (firefoxVersion < 7) {//firefox7 below
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
                                                                                                                  } else {//firefox7.0+ 
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
                                                                                                                  }
                                                                                                                  } else {
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                                  }
                                                                                                                  } else {
                                                                                                                  alert("only support" + allowExtention + "suffix");
                                                                                                                  fileObj.value = ""; //clear Selected file
                                                                                                                  if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                                  fileObj.select();
                                                                                                                  document.selection.clear();
                                                                                                                  }

                                                                                                                  }
                                                                                                                  }
                                                                                                                  function changeFile(elem) {
                                                                                                                  //file object , preview img tag id
                                                                                                                  previewImage(elem,'imagePreview')
                                                                                                                  }

                                                                                                                  </script>





                                                                                                                  <script>

                                                                                                                  function previewImage(fileObj, imgPreviewId) {
                                                                                                                  var allowExtention = ".jpg,.bmp,.gif,.png"; //allowed to upload file type
                                                                                                                  document.getElementById("hfAllowPicSuffix").value;
                                                                                                                  var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
                                                                                                                  var browserVersion = window.navigator.userAgent.toUpperCase();
                                                                                                                  if (allowExtention.indexOf(extention) > -1) {
                                                                                                                  if (fileObj.files) {
                                                                                                                  if (window.FileReader) {
                                                                                                                  var reader = new FileReader();
                                                                                                                  reader.onload = function (e) {
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
                                                                                                                  };
                                                                                                                  reader.readAsDataURL(fileObj.files[0]);
                                                                                                                  } else if (browserVersion.indexOf("SAFARI") > -1) {
                                                                                                                  alert("don't support Safari6.0 below broswer");
                                                                                                                  }
                                                                                                                  } else if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                                  if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                                  } else {//ie[7-9]
                                                                                                                  fileObj.select();
                                                                                                                  fileObj.blur();
                                                                                                                  var newPreview = document.getElementById(imgPreviewId);

                                                                                                                  newPreview.style.border = "solid 1px #eeeeee";
                                                                                                                  newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
                                                                                                                  newPreview.style.display = "block";

                                                                                                                  }
                                                                                                                  } else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
                                                                                                                  var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox/([d.]+)/)[1]);
                                                                                                                  if (firefoxVersion < 7) {//firefox7 below
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
                                                                                                                  } else {//firefox7.0+ 
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
                                                                                                                  }
                                                                                                                  } else {
                                                                                                                  document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                                                                                                                  }
                                                                                                                  } else {
                                                                                                                  alert("only support" + allowExtention + "suffix");
                                                                                                                  fileObj.value = ""; //clear Selected file
                                                                                                                  if (browserVersion.indexOf("MSIE") > -1) {
                                                                                                                  fileObj.select();
                                                                                                                  document.selection.clear();
                                                                                                                  }

                                                                                                                  }
                                                                                                                  }
                                                                                                                  function changeFile(elem) {
                                                                                                                  //file object , preview img tag id
                                                                                                                  previewImage(elem,'imagePreview')
                                                                                                                  }

                                                                                                                  </script>






                                                                                                                  share|improve this answer












                                                                                                                  share|improve this answer



                                                                                                                  share|improve this answer










                                                                                                                  answered Mar 28 '17 at 11:28









                                                                                                                  Steve JiangSteve Jiang

                                                                                                                  347313




                                                                                                                  347313























                                                                                                                      0














                                                                                                                      Try this






                                                                                                                      window.onload = function() {
                                                                                                                      if (window.File && window.FileList && window.FileReader) {
                                                                                                                      var filesInput = document.getElementById("uploadImage");
                                                                                                                      filesInput.addEventListener("change", function(event) {
                                                                                                                      var files = event.target.files;
                                                                                                                      var output = document.getElementById("result");
                                                                                                                      for (var i = 0; i < files.length; i++) {
                                                                                                                      var file = files[i];
                                                                                                                      if (!file.type.match('image'))
                                                                                                                      continue;
                                                                                                                      var picReader = new FileReader();
                                                                                                                      picReader.addEventListener("load", function(event) {
                                                                                                                      var picFile = event.target;
                                                                                                                      var div = document.createElement("div");
                                                                                                                      div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
                                                                                                                      "title='" + picFile.name + "'/>";
                                                                                                                      output.insertBefore(div, null);
                                                                                                                      });
                                                                                                                      picReader.readAsDataURL(file);
                                                                                                                      }

                                                                                                                      });
                                                                                                                      }
                                                                                                                      }

                                                                                                                      <input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
                                                                                                                      <div id="result" class="uploadPreview">








                                                                                                                      share|improve this answer




























                                                                                                                        0














                                                                                                                        Try this






                                                                                                                        window.onload = function() {
                                                                                                                        if (window.File && window.FileList && window.FileReader) {
                                                                                                                        var filesInput = document.getElementById("uploadImage");
                                                                                                                        filesInput.addEventListener("change", function(event) {
                                                                                                                        var files = event.target.files;
                                                                                                                        var output = document.getElementById("result");
                                                                                                                        for (var i = 0; i < files.length; i++) {
                                                                                                                        var file = files[i];
                                                                                                                        if (!file.type.match('image'))
                                                                                                                        continue;
                                                                                                                        var picReader = new FileReader();
                                                                                                                        picReader.addEventListener("load", function(event) {
                                                                                                                        var picFile = event.target;
                                                                                                                        var div = document.createElement("div");
                                                                                                                        div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
                                                                                                                        "title='" + picFile.name + "'/>";
                                                                                                                        output.insertBefore(div, null);
                                                                                                                        });
                                                                                                                        picReader.readAsDataURL(file);
                                                                                                                        }

                                                                                                                        });
                                                                                                                        }
                                                                                                                        }

                                                                                                                        <input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
                                                                                                                        <div id="result" class="uploadPreview">








                                                                                                                        share|improve this answer


























                                                                                                                          0












                                                                                                                          0








                                                                                                                          0







                                                                                                                          Try this






                                                                                                                          window.onload = function() {
                                                                                                                          if (window.File && window.FileList && window.FileReader) {
                                                                                                                          var filesInput = document.getElementById("uploadImage");
                                                                                                                          filesInput.addEventListener("change", function(event) {
                                                                                                                          var files = event.target.files;
                                                                                                                          var output = document.getElementById("result");
                                                                                                                          for (var i = 0; i < files.length; i++) {
                                                                                                                          var file = files[i];
                                                                                                                          if (!file.type.match('image'))
                                                                                                                          continue;
                                                                                                                          var picReader = new FileReader();
                                                                                                                          picReader.addEventListener("load", function(event) {
                                                                                                                          var picFile = event.target;
                                                                                                                          var div = document.createElement("div");
                                                                                                                          div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
                                                                                                                          "title='" + picFile.name + "'/>";
                                                                                                                          output.insertBefore(div, null);
                                                                                                                          });
                                                                                                                          picReader.readAsDataURL(file);
                                                                                                                          }

                                                                                                                          });
                                                                                                                          }
                                                                                                                          }

                                                                                                                          <input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
                                                                                                                          <div id="result" class="uploadPreview">








                                                                                                                          share|improve this answer













                                                                                                                          Try this






                                                                                                                          window.onload = function() {
                                                                                                                          if (window.File && window.FileList && window.FileReader) {
                                                                                                                          var filesInput = document.getElementById("uploadImage");
                                                                                                                          filesInput.addEventListener("change", function(event) {
                                                                                                                          var files = event.target.files;
                                                                                                                          var output = document.getElementById("result");
                                                                                                                          for (var i = 0; i < files.length; i++) {
                                                                                                                          var file = files[i];
                                                                                                                          if (!file.type.match('image'))
                                                                                                                          continue;
                                                                                                                          var picReader = new FileReader();
                                                                                                                          picReader.addEventListener("load", function(event) {
                                                                                                                          var picFile = event.target;
                                                                                                                          var div = document.createElement("div");
                                                                                                                          div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
                                                                                                                          "title='" + picFile.name + "'/>";
                                                                                                                          output.insertBefore(div, null);
                                                                                                                          });
                                                                                                                          picReader.readAsDataURL(file);
                                                                                                                          }

                                                                                                                          });
                                                                                                                          }
                                                                                                                          }

                                                                                                                          <input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
                                                                                                                          <div id="result" class="uploadPreview">








                                                                                                                          window.onload = function() {
                                                                                                                          if (window.File && window.FileList && window.FileReader) {
                                                                                                                          var filesInput = document.getElementById("uploadImage");
                                                                                                                          filesInput.addEventListener("change", function(event) {
                                                                                                                          var files = event.target.files;
                                                                                                                          var output = document.getElementById("result");
                                                                                                                          for (var i = 0; i < files.length; i++) {
                                                                                                                          var file = files[i];
                                                                                                                          if (!file.type.match('image'))
                                                                                                                          continue;
                                                                                                                          var picReader = new FileReader();
                                                                                                                          picReader.addEventListener("load", function(event) {
                                                                                                                          var picFile = event.target;
                                                                                                                          var div = document.createElement("div");
                                                                                                                          div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
                                                                                                                          "title='" + picFile.name + "'/>";
                                                                                                                          output.insertBefore(div, null);
                                                                                                                          });
                                                                                                                          picReader.readAsDataURL(file);
                                                                                                                          }

                                                                                                                          });
                                                                                                                          }
                                                                                                                          }

                                                                                                                          <input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
                                                                                                                          <div id="result" class="uploadPreview">





                                                                                                                          window.onload = function() {
                                                                                                                          if (window.File && window.FileList && window.FileReader) {
                                                                                                                          var filesInput = document.getElementById("uploadImage");
                                                                                                                          filesInput.addEventListener("change", function(event) {
                                                                                                                          var files = event.target.files;
                                                                                                                          var output = document.getElementById("result");
                                                                                                                          for (var i = 0; i < files.length; i++) {
                                                                                                                          var file = files[i];
                                                                                                                          if (!file.type.match('image'))
                                                                                                                          continue;
                                                                                                                          var picReader = new FileReader();
                                                                                                                          picReader.addEventListener("load", function(event) {
                                                                                                                          var picFile = event.target;
                                                                                                                          var div = document.createElement("div");
                                                                                                                          div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
                                                                                                                          "title='" + picFile.name + "'/>";
                                                                                                                          output.insertBefore(div, null);
                                                                                                                          });
                                                                                                                          picReader.readAsDataURL(file);
                                                                                                                          }

                                                                                                                          });
                                                                                                                          }
                                                                                                                          }

                                                                                                                          <input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
                                                                                                                          <div id="result" class="uploadPreview">






                                                                                                                          share|improve this answer












                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer










                                                                                                                          answered Dec 21 '17 at 4:44









                                                                                                                          Nisal EduNisal Edu

                                                                                                                          2,90021423




                                                                                                                          2,90021423























                                                                                                                              -1














                                                                                                                              function assignFilePreviews() {
                                                                                                                              $('input[data-previewable="true"]').change(function() {
                                                                                                                              var prvCnt = $(this).attr('data-preview-container');
                                                                                                                              if (prvCnt) {
                                                                                                                              if (this.files && this.files[0]) {
                                                                                                                              var reader = new FileReader();
                                                                                                                              reader.onload = function(e) {
                                                                                                                              var img = $('<img>');
                                                                                                                              img.attr('src', e.target.result);
                                                                                                                              img.error(function() {
                                                                                                                              $(prvCnt).html('');
                                                                                                                              });
                                                                                                                              $(prvCnt).html('');
                                                                                                                              img.appendTo(prvCnt);
                                                                                                                              }
                                                                                                                              reader.readAsDataURL(this.files[0]);
                                                                                                                              }
                                                                                                                              }
                                                                                                                              });
                                                                                                                              }
                                                                                                                              $(document).ready(function() {
                                                                                                                              assignFilePreviews();
                                                                                                                              });


                                                                                                                              HTML



                                                                                                                              <input type="file" data-previewable="true" data-preview-container=".prd-img-prv" />
                                                                                                                              <div class = "prd-img-prv"></div>


                                                                                                                              This also handles case when file with invalid type ( ex. pdf ) is choosen






                                                                                                                              share|improve this answer






























                                                                                                                                -1














                                                                                                                                function assignFilePreviews() {
                                                                                                                                $('input[data-previewable="true"]').change(function() {
                                                                                                                                var prvCnt = $(this).attr('data-preview-container');
                                                                                                                                if (prvCnt) {
                                                                                                                                if (this.files && this.files[0]) {
                                                                                                                                var reader = new FileReader();
                                                                                                                                reader.onload = function(e) {
                                                                                                                                var img = $('<img>');
                                                                                                                                img.attr('src', e.target.result);
                                                                                                                                img.error(function() {
                                                                                                                                $(prvCnt).html('');
                                                                                                                                });
                                                                                                                                $(prvCnt).html('');
                                                                                                                                img.appendTo(prvCnt);
                                                                                                                                }
                                                                                                                                reader.readAsDataURL(this.files[0]);
                                                                                                                                }
                                                                                                                                }
                                                                                                                                });
                                                                                                                                }
                                                                                                                                $(document).ready(function() {
                                                                                                                                assignFilePreviews();
                                                                                                                                });


                                                                                                                                HTML



                                                                                                                                <input type="file" data-previewable="true" data-preview-container=".prd-img-prv" />
                                                                                                                                <div class = "prd-img-prv"></div>


                                                                                                                                This also handles case when file with invalid type ( ex. pdf ) is choosen






                                                                                                                                share|improve this answer




























                                                                                                                                  -1












                                                                                                                                  -1








                                                                                                                                  -1







                                                                                                                                  function assignFilePreviews() {
                                                                                                                                  $('input[data-previewable="true"]').change(function() {
                                                                                                                                  var prvCnt = $(this).attr('data-preview-container');
                                                                                                                                  if (prvCnt) {
                                                                                                                                  if (this.files && this.files[0]) {
                                                                                                                                  var reader = new FileReader();
                                                                                                                                  reader.onload = function(e) {
                                                                                                                                  var img = $('<img>');
                                                                                                                                  img.attr('src', e.target.result);
                                                                                                                                  img.error(function() {
                                                                                                                                  $(prvCnt).html('');
                                                                                                                                  });
                                                                                                                                  $(prvCnt).html('');
                                                                                                                                  img.appendTo(prvCnt);
                                                                                                                                  }
                                                                                                                                  reader.readAsDataURL(this.files[0]);
                                                                                                                                  }
                                                                                                                                  }
                                                                                                                                  });
                                                                                                                                  }
                                                                                                                                  $(document).ready(function() {
                                                                                                                                  assignFilePreviews();
                                                                                                                                  });


                                                                                                                                  HTML



                                                                                                                                  <input type="file" data-previewable="true" data-preview-container=".prd-img-prv" />
                                                                                                                                  <div class = "prd-img-prv"></div>


                                                                                                                                  This also handles case when file with invalid type ( ex. pdf ) is choosen






                                                                                                                                  share|improve this answer















                                                                                                                                  function assignFilePreviews() {
                                                                                                                                  $('input[data-previewable="true"]').change(function() {
                                                                                                                                  var prvCnt = $(this).attr('data-preview-container');
                                                                                                                                  if (prvCnt) {
                                                                                                                                  if (this.files && this.files[0]) {
                                                                                                                                  var reader = new FileReader();
                                                                                                                                  reader.onload = function(e) {
                                                                                                                                  var img = $('<img>');
                                                                                                                                  img.attr('src', e.target.result);
                                                                                                                                  img.error(function() {
                                                                                                                                  $(prvCnt).html('');
                                                                                                                                  });
                                                                                                                                  $(prvCnt).html('');
                                                                                                                                  img.appendTo(prvCnt);
                                                                                                                                  }
                                                                                                                                  reader.readAsDataURL(this.files[0]);
                                                                                                                                  }
                                                                                                                                  }
                                                                                                                                  });
                                                                                                                                  }
                                                                                                                                  $(document).ready(function() {
                                                                                                                                  assignFilePreviews();
                                                                                                                                  });


                                                                                                                                  HTML



                                                                                                                                  <input type="file" data-previewable="true" data-preview-container=".prd-img-prv" />
                                                                                                                                  <div class = "prd-img-prv"></div>


                                                                                                                                  This also handles case when file with invalid type ( ex. pdf ) is choosen







                                                                                                                                  share|improve this answer














                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer








                                                                                                                                  edited Oct 28 '18 at 9:48









                                                                                                                                  Mohammad

                                                                                                                                  15.6k123461




                                                                                                                                  15.6k123461










                                                                                                                                  answered Apr 10 '17 at 19:25









                                                                                                                                  Jinu Joseph DanielJinu Joseph Daniel

                                                                                                                                  1,930104479




                                                                                                                                  1,930104479























                                                                                                                                      -2














                                                                                                                                      for my app, with encryped GET url parameters, only this worked. I always got a TypeError: $(...) is null.
                                                                                                                                      Taken from https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL






                                                                                                                                      function previewFile() {
                                                                                                                                      var preview = document.querySelector('img');
                                                                                                                                      var file = document.querySelector('input[type=file]').files[0];
                                                                                                                                      var reader = new FileReader();

                                                                                                                                      reader.addEventListener("load", function () {
                                                                                                                                      preview.src = reader.result;
                                                                                                                                      }, false);

                                                                                                                                      if (file) {
                                                                                                                                      reader.readAsDataURL(file);
                                                                                                                                      }
                                                                                                                                      }

                                                                                                                                      <input type="file" onchange="previewFile()"><br>
                                                                                                                                      <img src="" height="200" alt="Image preview...">








                                                                                                                                      share|improve this answer




























                                                                                                                                        -2














                                                                                                                                        for my app, with encryped GET url parameters, only this worked. I always got a TypeError: $(...) is null.
                                                                                                                                        Taken from https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL






                                                                                                                                        function previewFile() {
                                                                                                                                        var preview = document.querySelector('img');
                                                                                                                                        var file = document.querySelector('input[type=file]').files[0];
                                                                                                                                        var reader = new FileReader();

                                                                                                                                        reader.addEventListener("load", function () {
                                                                                                                                        preview.src = reader.result;
                                                                                                                                        }, false);

                                                                                                                                        if (file) {
                                                                                                                                        reader.readAsDataURL(file);
                                                                                                                                        }
                                                                                                                                        }

                                                                                                                                        <input type="file" onchange="previewFile()"><br>
                                                                                                                                        <img src="" height="200" alt="Image preview...">








                                                                                                                                        share|improve this answer


























                                                                                                                                          -2












                                                                                                                                          -2








                                                                                                                                          -2







                                                                                                                                          for my app, with encryped GET url parameters, only this worked. I always got a TypeError: $(...) is null.
                                                                                                                                          Taken from https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL






                                                                                                                                          function previewFile() {
                                                                                                                                          var preview = document.querySelector('img');
                                                                                                                                          var file = document.querySelector('input[type=file]').files[0];
                                                                                                                                          var reader = new FileReader();

                                                                                                                                          reader.addEventListener("load", function () {
                                                                                                                                          preview.src = reader.result;
                                                                                                                                          }, false);

                                                                                                                                          if (file) {
                                                                                                                                          reader.readAsDataURL(file);
                                                                                                                                          }
                                                                                                                                          }

                                                                                                                                          <input type="file" onchange="previewFile()"><br>
                                                                                                                                          <img src="" height="200" alt="Image preview...">








                                                                                                                                          share|improve this answer













                                                                                                                                          for my app, with encryped GET url parameters, only this worked. I always got a TypeError: $(...) is null.
                                                                                                                                          Taken from https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL






                                                                                                                                          function previewFile() {
                                                                                                                                          var preview = document.querySelector('img');
                                                                                                                                          var file = document.querySelector('input[type=file]').files[0];
                                                                                                                                          var reader = new FileReader();

                                                                                                                                          reader.addEventListener("load", function () {
                                                                                                                                          preview.src = reader.result;
                                                                                                                                          }, false);

                                                                                                                                          if (file) {
                                                                                                                                          reader.readAsDataURL(file);
                                                                                                                                          }
                                                                                                                                          }

                                                                                                                                          <input type="file" onchange="previewFile()"><br>
                                                                                                                                          <img src="" height="200" alt="Image preview...">








                                                                                                                                          function previewFile() {
                                                                                                                                          var preview = document.querySelector('img');
                                                                                                                                          var file = document.querySelector('input[type=file]').files[0];
                                                                                                                                          var reader = new FileReader();

                                                                                                                                          reader.addEventListener("load", function () {
                                                                                                                                          preview.src = reader.result;
                                                                                                                                          }, false);

                                                                                                                                          if (file) {
                                                                                                                                          reader.readAsDataURL(file);
                                                                                                                                          }
                                                                                                                                          }

                                                                                                                                          <input type="file" onchange="previewFile()"><br>
                                                                                                                                          <img src="" height="200" alt="Image preview...">





                                                                                                                                          function previewFile() {
                                                                                                                                          var preview = document.querySelector('img');
                                                                                                                                          var file = document.querySelector('input[type=file]').files[0];
                                                                                                                                          var reader = new FileReader();

                                                                                                                                          reader.addEventListener("load", function () {
                                                                                                                                          preview.src = reader.result;
                                                                                                                                          }, false);

                                                                                                                                          if (file) {
                                                                                                                                          reader.readAsDataURL(file);
                                                                                                                                          }
                                                                                                                                          }

                                                                                                                                          <input type="file" onchange="previewFile()"><br>
                                                                                                                                          <img src="" height="200" alt="Image preview...">






                                                                                                                                          share|improve this answer












                                                                                                                                          share|improve this answer



                                                                                                                                          share|improve this answer










                                                                                                                                          answered Aug 1 '17 at 6:07









                                                                                                                                          Robert TheSimRobert TheSim

                                                                                                                                          6012




                                                                                                                                          6012

















                                                                                                                                              protected by Community Feb 11 '13 at 14:44



                                                                                                                                              Thank you for your interest in this question.
                                                                                                                                              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                                                              Would you like to answer one of these unanswered questions instead?



                                                                                                                                              Popular posts from this blog

                                                                                                                                              404 Error Contact Form 7 ajax form submitting

                                                                                                                                              How to know if a Active Directory user can login interactively

                                                                                                                                              TypeError: fit_transform() missing 1 required positional argument: 'X'