Yes I am back, was quite busy for almost the whole year but yes I am still doing programming, a lot of it, in fact I was busy with two projects hence I haven’t posted for quite sometime. Today I will just post a simple How To that might be really helpful to some that are using the Kendo Upload.
How many of you who are using this amazing control but was wondering how would you display a thumbnail photo of an image you are uploading? That was one of the challenges I faced when I was creating a shopping cart system where the user uploads photos of the product, this means a user will not have to decide whats uploaded based on the filename but now they can see a preview alongside the name like this image below.
How to achieve that is quite simple just by using Events on the Kendo upload eventually firing a JavaScript On Select that adds a preview on the side of the filename.
First element would be you view which will work regardless of whether you use Auto Upload, Async upload or not. All you need to do is call the OnSelect Javascript to do its thing on firing the event.
<div class="form-group"> @Html.LabelFor(model => model.ProductImages) @(Html.Kendo().Upload() .Name("ProductImages") .HtmlAttributes(new { aria_label = "ProductImages" }) .Async(a => a .Save("SaveAttachment", "ProductAttachments", new { productId = Model.ProductId }) .Remove("RemoveAttachment", "ProductAttachments", new { productId = Model.ProductId }) .AutoUpload(true)) .Files(files => { if (Model.ProductImagesViewModel != null) { foreach (var f in Model.ProductImagesViewModel) { files.Add().Name(f.FileName).Extension(f.FileExtension).Size((long)f.FileSize); } } }).Events(e => e.Select("onSelect")) ) </div>
Next you need the JavaScript that loop through each file then adds a Preview by rendering its raw format.
<script type="text/javascript"> function onSelect(e) { var fileInfos = e.files; var wrapper = this.wrapper; fileInfos.forEach(function (fileInfo) { 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-extension-wrapper") .replaceWith(preview); }; reader.readAsDataURL(raw); } } </script>
Finally to make it pretty you need a style for that class for “image-preview” and put the thumbnail on its side.
<style> .image-preview { position: relative; vertical-align: top; height: 45px; } </style>
That’s it, easy and simple.