Search code examples
javascripthtmljqueryasp.net-core-mvcdropify

How to set default image in dropify ? ( base64 image format )


I am using the https://github.com/JeremyFagis/dropify plugin for image upload and wish the <input /> element show a thumbnail if there is already a file uploaded for the specified image.

I have found the How to set default image in dropify using jquery and ajax only to work but as I am getting images that are saved in the database in base64 format from server this solution didn't solve my issue.

p.s. I am using .Net Core mvc and Javascript/jQuery

@if (Model.Product.RequiredImagesCount >= 1)
    {
        <form action="@($"/PrintOrder/OrderImageUpload?orderId={Model.Id}&imagePosition=0")" method="post" class="form-horizontal" enctype="multipart/form-data">

            <input type="file" name="File" class="dropify" data-max-file-size="50M" data-show-remove="false" data-default-file="" onchange="SubmitForm($(this));" />

            <div class="progress progress-striped d-none">
                <div class="progress-bar progress-bar-success">0%</div>
            </div>
        </form>
    }

Solution

  • How to set default image in dropify ? ( base64 image format )

    To set default image in dropify using a base64 encoded image that is stored in your database, you can refer to the following approach.

    <input type="file" name="File" class="dropify" data-max-file-size="50M" data-show-remove="false" data-default-file="" onchange="SubmitForm($(this));" />
    

    JS code

    $(function () {
        $('.dropify').dropify();
    
        resetPreview('File', 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4RI....',
            'Image.jpg');
    })
    
    function resetPreview(name, src, fname = '') {
        let input = $('input[name="' + name + '"]');
        let wrapper = input.closest('.dropify-wrapper');
        let preview = wrapper.find('.dropify-preview');
        let filename = wrapper.find('.dropify-filename-inner');
        let render = wrapper.find('.dropify-render').html('');
    
        input.val('').attr('title', fname);
        wrapper.removeClass('has-error').addClass('has-preview');
        filename.html(fname);
    
        render.append($('<img />').attr('src', src).css('max-height', input.data('height') || ''));
        preview.fadeIn();
    }
    

    Test Result

    enter image description here