GravityForms: How to Add Image Preview to File Upload Field
Getting your Trinity Audio player ready...
|
Scenario: You have a gravity form with a file upload field. Only the name of the image is displayed.
Goal: Show an image preview for each file.
Difficulty: Medium
Coding Required: Yes
First, you will need to open your functions.php file.
Once you have opened up your functions.php file, add the following code:
<php /** * Upload image action for Gravity Forms * This script displays the thumbnail upon image upload for multi file field. * Change the ID to your form ID */ function wd_gravity_image_thumb_upload() { // change this to your page ID if ( is_page('1') ) { // change this to your form ID $upload_path = GFFormsModel::get_upload_url( '1' ); ?> <script type="text/javascript"> jQuery(document).ready(function($) { gform.addFilter('gform_file_upload_markup', function (html, file, up, strings, imagesUrl) { //Path of your temp file var myFilePath = '<?php echo $upload_path . '/tmp/'; ?>'; var formId = up.settings.multipart_params.form_id, fieldId = up.settings.multipart_params.field_id; var fileName = up.settings.multipart_params.gform_unique_id + '_input_' + fieldId +'_'+ file.target_name; var fid = "fid"+ Math.ceil((Math.random() * (10000 - 1000)) + 1000); //Converting Image to the base64 function convertImgToBase64URL(url, callback, outputFormat){ var img = new Image(); img.crossOrigin = 'Anonymous'; img.onload = function(){ var canvas = document.createElement('CANVAS'), ctx = canvas.getContext('2d'), dataURL; canvas.height = (300 * img.height)/img.width; canvas.width = 300; //img.width; ctx.drawImage(img, 0, 0, canvas.width, canvas.height); dataURL = canvas.toDataURL(outputFormat); callback(dataURL); canvas = null; }; img.src = url; } convertImgToBase64URL( myFilePath + fileName , function(base64Img){ var ffid = "#"+fid; $(ffid).attr("src", base64Img); console.log('RESULT:', base64Img); }); html = '<img id="'+fid+"\" src='' style='width:100%;height:auto;'/><img class='gform_delete' " + "src='" + imagesUrl + "/delete.png' "+ "onclick='gformDeleteUploadedFile(" + formId + "," + fieldId + ", this);' " + "alt='" + strings.delete_file + "' title='" + strings.delete_file + "' />"; return html; }); }); </script> <?php } } add_action('wp_head','wd_gravity_image_thumb_upload');
Now that we’ve created the image preview, let’s style it a bit. In your .css file add the following code:
/*** change to your field ID ***/ #gform_preview_1_1{ overflow: hidden; margin: 0 -1%; } #gform_preview_1_1 .ginput_preview{ float: left; width: 23%; margin: 1%; display: block; position: relative; margin-bottom: 15px; } #gform_preview_1_1 .gform_delete{ position: absolute; top: 10px; right: 10px; background-color: white; border-radius: 20px; padding: 10px; }
There you have it!