How can I preview an uploaded image?

Normally when you upload an image it isn't possible to see it until after the form is submitted. However HTML5 supports a FileReader that makes this possible. User fibernet found  way to use that in ChronoForms v5 and this FAQ is a development of his ideas.

In your form you need to have a File Field element and to give it an ID in the element settings e.g. image_file

In the Setup tab drag a Load CSS into the On Load event before the HTML (Render form) action and add this CSS to format the image display box:

#imagePreview {
  width: 270px;
  height: 180px;
  padding: 12px;
  margin-top: 6px;
  background-position: center center;
  background-size: contain;
  background-repeat: no-repeat;
  background-clip: padding-box;
  border: 1px solid silver;
  -webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
  display: inline-block;
}

You can adjust and adapt this CSS later to suit your site. I have set it to match the width of my File input element.

Next, add a Load JavaScript action in the same way and add this JavaScript:

jQuery(document).ready(function(jQ) {
  var uploadFile;
  // edit this line to the id of the file element
  uploadFile = 'image_file';

  uploadFile = jQ('#'+uploadFile);
  uploadFile.after("<div id='imagePreview'></div>");
  jQ('#imagePreview').hide();
  uploadFile.on('click', function() {
    jQ('#imagePreview').hide();
  });

  uploadFile.on('change', function() {
    var files, reader;
    files = !!this.files ? this.files : [];
    if ( !files.length || !window.FileReader ) {
      return; // no file selected, or no FileReader support
    }

    if ( /^image/.test(files[0].type) ) { // only image file
      reader = new FileReader(); // instance of the FileReader
      reader.readAsDataURL(files[0]); // read the local file
      reader.onloadend = function() { // set image data as background of div
        jQ('#imagePreview').css('background-image', 'url(' + this.result + ')');
        jQ('#imagePreview').show();
      }
    }
  });
});

Change the image_file text to match the id of your file upload element.

Save your form and test.

If your browser does not support HTML 5 then you should see nothing different.

If it does support HTML5 then when you select an image file a box will be displayed under the file upload element and the image will be uploaded and displayed - sized to fit the box. 

If you click in the file upload element the image is hidden until you make a new selection.

Category: ChronoForms v5

Comments:

You need to login to be able to post a comment.