JumpStart # 22– Image preview for input file type using HTML5 File API

In this short tutorial we are going to see how to preview an image when selected for upload using input file type. We use HTML5 File API and its FileReader to read the file and display it in the image tag. FileReader’s readAsDataURL will start reading the contents of the specified Blob, which may be a File. When the read operation is finished, onloadend callback will be called and the raw binary data of the file contains in the result attribute.

Create a MVC4 webapplication. Add a controller with name ImageController to the controllers folder. Then have the default index view and create a view to it by right clicking on the view name and select ‘Add View’. So the controller looks like –

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class ImageController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

 

And in the view, paste the following code –

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<input type="file" name="image" onchange="preview(this)" accept="image/*" /><br />
<img id="image01" src="~/Images/icon.jpg" />
<script type="text/javascript">
    function preview(fileInput) {
        if (fileInput.files && fileInput.files[0]) {
            var reader = new FileReader();
            reader.onloadend = function (e) {
                $('#image01').attr('src', e.target.result);
            }
            //readAsDataURL will start reading the contents of the specified Blob, which may be a File. 
            // When the read operation is finished, the readyState property will become DONE, and the 
            // onloadend callback, if any, will be called. At that time, the result attribute contains 
            // the raw binary data from the file.
            reader.readAsDataURL(fileInput.files[0]);
        }
    }
</script>

 

Make sure you have a dummy image icon.jpg (any image, it acts just like a image placeholder) in the Images folder of the solution.

Run the application and navigate the /Image/Index url.

image

Now select any image from local system. It will be previewed immediately in the image control.

image

Thus a simple image preview has been achieved.

Happy Coding!!!

You may also like...