Wednesday 12 February 2020

Preview and upload image using Javascript

Image preview is a great feature for user to check their image before upload whether the correct image is going to upload or if the image looks

If you want 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.

The question is "How can I do this?"

if you have been told, "unless you use Gears or another plugin you cannot manipulate the image inside the browser" that's false.

Here's a simple solution that doesn't use jquery, is pure javascript.

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:

Please take a look at the sample code below:

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

Read carefully: readAsDataURL and createObjectURL will cache an image in the browser, then return a base64 encoded string which references the image location in the 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.
to avoid memory issues you should call URL.revokeObjectURL when you are done with your blob

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

Previous Post
Next Post

post written by:

0 Comments:

Hit me with a comment!