Click here to Skip to main content
15,913,140 members
Articles / Web Development / HTML
Tip/Trick

jQuery Image Upload with Image Perview

Rate me:
Please Sign up or sign in to vote.
4.50/5 (4 votes)
6 Oct 2015CPOL1 min read 16.4K   11   1
A simple jQuery image upload functionality to upload and preview images with hidden fileupload control.

Introduction

In this article I will be explaining how to create a simple image upload functoining with preview feature without explicitly having the fileupload control button visible to the user using MVC and jQuery.

Background

User click's on Image control, the Image control's click event is hooked up with the click event of the hidden file upload control which opens up the file dialog box and the user navigates to the image to upload, Image is displayed in the Image control for preview using the FileReader object. Finally the user can hit the submit button to save the image.

Lets jump directly into to code to see whats happening.

Using the code

Step 1 : Add reference to jQuery file

C++
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.min.js"></script>

 

Step 2 :   Add { enctype = "multipart/form-data" } in the form element of the page and add the html controls. In this example the form posts back to Index action method of the home controller.

Here we have three html controls, Image control, File upload control (hidden) and Submit button.

C#
@*add 'new { enctype = "multipart/form-data" }' in the form*@
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="row">
        <div class="col-md-4">

            @*Image Control to display/Preview selected Image *@
            <img id="MyProfileImage" name="MyProfileImage" src="~/Content/Images/DefaultImage.png" height="100" width="100" />

            @*File Upload control --  Visibility hidden*@
            <input type="file" name="fileUploaderControl" id="fileUploaderControl" style="display:none;">

            @*Submit button to post the Image back to server side for further processing*@
            <input type="submit" value="Send Profile image to server for further processing." />

        </div>
    </div>
}

Step 3 : In jQuery, we are raising the click event of the file upload control when the user clicks on the image. 

In the java script file, bind the click event of the file upload control on the click event of the Image.

In the change event of the file upload control, use the FileReader object to read the file uploaded as DataURL and update the source attribute of the image control with it.

<script type="text/javascript">

    //Hooking the click of the fileupload control with Image.
    $(document).ready(function () {
        $('#MyProfileImage').click(function () {
            $('#fileUploaderControl').click();
        });
    });

    //Using FileReader to convert the image as dataurl.
    $(document).ready(function () {
        $("#fileUploaderControl").change(function () {
            var file = document.getElementById("fileUploaderControl").files[0];
            var readImg = new FileReader();
            readImg.readAsDataURL(file);
            readImg.onload = function (e) {
                $('#MyProfileImage').attr('src', e.target.result).fadeIn();
            }
        });
    });
</script>

</script>

Finally, the submit button posts the form back to the Index action method of the home controller, where we can get the uploaded image in the HttpPostedFileBase object and use to save. Below is the code snippet from the controller.

C#
[HttpPost]
        public ActionResult Index(HttpPostedFileBase file, string button)
        {
            try
            {
                //Get the file name
                string filename = System.IO.Path.GetFileName(file.FileName);

                //Save the file in server Images folder
                file.SaveAs(Server.MapPath("~/Images/" + filename));
                
                string filepathtosave = "Images/" + filename;
                 
                //TODO : CODE TO SAVE IMAGE DETAIL IN DATABASE
                
                ViewBag.Message = "File Uploaded successfully.";
            }
            catch
            {
                ViewBag.Message = "Error while uploading the files.";
            }
            return View();
        }

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- No messages could be retrieved (timeout) --