next2u next2u - 6 months ago 47
jQuery Question

Preview the uploaded image in product page in Opencart

I am using Opencart Version 2.0.3.1.

Customer can upload

image (upload file option)
in product page. I want to
preview the uploaded image
in the same page. The uploaded image is saved to
system/upload
folder and renamed with the filename+some string.

How can I preview the uploaded image.

The file upload button code is:(catalog/view/theme/default/template/product.product.tpl)

<?php if ($option['type'] == 'file') { ?>
<div class="form-group<?php echo ($option['required'] ? ' required' : ''); ?>">
<label class="control-label"><?php echo $option['name']; ?></label>
<button type="button" id="button-upload<?php echo $option['product_option_id']; ?>" data-loading-text="<?php echo $text_loading; ?>" class="btn btn-default btn-block"><i class="fa fa-upload"></i> <?php echo $button_upload; ?></button>
<input type="hidden" name="option[<?php echo $option['product_option_id']; ?>]" value="" id="input-option<?php echo $option['product_option_id']; ?>" />
</div>
<?php } ?>

Answer

Not optimal solution but you can try this one.

Add

<img id="filePreview" style="display:none;">

After

<?php if ($option['type'] == 'file') { ?>

Add

var ref = '';

$(document).on('change','input[name="file"]',function(){
    ref = this;
});

Before

$('button[id^=\'button-upload\']').on('click', function() {

In ajax request of file upload, add this in success function

if (json['error']) {
        ref = '';
        $(node).parent().find('input').after('<div class="text-danger">' + json['error'] + '</div>');
}

if (json['success']) {
    alert(json['success']);
    showImagePreview(ref);
    $(node).parent().find('input').attr('value', json['code']);
}

The show preview function is

function showImagePreview(input){

 if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
        $('#filePreview').attr('src',e.target.result);
        $('#filePreview').show();
    }
    reader.readAsDataURL(input.files[0]);
 }
}

Hope it will work :)