New to Kendo UI for jQueryStart a free 30-day trial

Add Image Previews before Uploading Files in the Upload

Environment

ProductProgress® Kendo UI® Upload for jQuery
Operating SystemWindows 10 64bit
Visual Studio VersionVisual Studio 2017
Preferred LanguageJavaScript

Description

How can I add an image preview for the user before the file is uploaded in the Kendo UI Upload?

Solution

The following example demonstrates how to add an image preview and read the file in the select event of the Upload.

<div id="example">
    <h3>Add image preview before uploading file</h3>
		<input type="file" id="files">

    <script>
      $(document).ready(function() {
        $("#files").kendoUpload({
          async: {
            saveUrl: "save",
            removeUrl: "remove",
            autoUpload: false
          },
          multiple: false,
          select: function(e) {
            var fileInfo = e.files[0];
            var wrapper = this.wrapper;

            setTimeout(function(){
              addPreview(fileInfo, wrapper);
            });
          }
        });
      });

      function addPreview(file, wrapper) {
        var raw = file.rawFile;
        var reader  = new FileReader();

        if (raw) {
          reader.onloadend = function () {
            var preview = $("<img class='image-preview'>").attr("src", this.result);

            wrapper.find(".k-file[data-uid='" + file.uid + "'] .k-file-group-wrapper")
              .replaceWith(preview);
          };

          reader.readAsDataURL(raw);
        }
      }
    </script>
    <style>
      .image-preview {
        position: relative;
        vertical-align: top;
        height: 45px;
      }
    </style>
  </div>

See Also