Last Updated: February 25, 2016
·
1.739K
· pniemczyk

Image preview in javascript (coffeescript)

Preview images with file types protection and size.

Demo

coffescript:

EXT = /(\.|\/)(gif|jpe?g|png)$/i
$fileInput = $('#file')

previewImage = ->
    file = $fileInput[0].files[0] if ($fileInput[0].files && $fileInput[0].files[0])
    return unless file?

    $imagePreview = $('#image')
    return $imagePreview.css('background-image', "").text('this file is not supported') unless file.name.match(EXT)
    return $imagePreview.css('background-image', "").text('image size to large (> 1MB)') if file.size > 1048576

    if (window.File && window.FileReader && window.FileList && window.Blob)
        reader = new FileReader()
        reader.onload = (e) => $imagePreview.css('background-image', "url(#{e.target.result})").text('')
        reader.readAsDataURL(file)
      else
        $imageContainer.css('background-image', "none")
        alert 'Unsupported preview image in this browser. Change it!'

$fileInput.change(previewImage)
$('#preview').on 'click', (e) ->
    e.preventDefault()
    $fileInput.trigger('click')

javascript:


var $fileInput, EXT, previewImage;

EXT = /(\.|\/)(gif|jpe?g|png)$/i;

$fileInput = $('#file');

previewImage = function() {
  var $imagePreview, file, reader;
  if ($fileInput[0].files && $fileInput[0].files[0]) {
    file = $fileInput[0].files[0];
  }
  if (file == null) {
    return;
  }
  $imagePreview = $('#image');
  if (!file.name.match(EXT)) {
    return $imagePreview.css('background-image', "").text('this file is not supported');
  }
  if (file.size > 1048576) {
    return $imagePreview.css('background-image', "").text('image size to large (> 1MB)');
  }
  if (window.File && window.FileReader && window.FileList && window.Blob) {
    reader = new FileReader();
    reader.onload = (function(_this) {
      return function(e) {
        return $imagePreview.css('background-image', "url(" + e.target.result + ")").text('');
      };
    })(this);
    return reader.readAsDataURL(file);
  } else {
    $imageContainer.css('background-image', "none");
    return alert('Unsupported preview image in this browser. Change it!');
  }
};

$fileInput.change(previewImage);

$('#preview').on('click', function(e) {
  e.preventDefault();
  return $fileInput.trigger('click');
});