Wednesday, 27 December 2017

Upload file using jquery filereader

Step 1: Add following html code:

<div class="row form-group">
    <label class="col-md-2">Upload Image</label>
    <div class="col-md-3">
        <input type="file" class="" multiple onchange="previewFile()" />
    </div>
    <div class="col-md-7" id="divImages">
    </div>
</div>

Step 2: Add following js code:

function previewFile() {
            var files = document.querySelector('input[type=file]').files;
            processFile(files, 0);
        }


function processFile(files, count) {
            if (files.length == count)
                return;

            var reader = new FileReader();
            var file = files[count];

            reader.addEventListener("load", function () {
                $("#divImages").append('<div class="div-img"><img onclick="setMainImage(this)" class="campaign-image" title="Click to set as main image." src=' + reader.result + ' alt="Image preview..."></br><button style="margin-top: 10px;" class="btn btn-danger" onclick="deleteImage(this)">Delete</button></div>');
                count++;
                processFile(files, count);
            }, false);

            if (file) {
                reader.readAsDataURL(file);
            }
        }

No comments:

Post a Comment