[X]

Asp.Net - Bindable image upload web user control with image preview

 

Developing Image upload web user control with image preview in asp.net:

As a developer working for content management system/ecommerce/blogging/social sites development, one most frequent task is image upload.

We spend lots of time dragging/dropping file control, upload button and writing code to check for file extension and then uploading the image on the site in specified directory location.

And if one wants to show the preview this task gets even much lengthier.

Keeping this in mind I wrote a web user control which is generic in nature and can be just used on any page with little configuration and offcourse no code rewriting.

Also this user control is bindable and has image preview if choosen. So this can be used inside data grid view/form view/list view/repeater/details view/data list control by just dragigng and dropping.

So lets start building image upload web user control with preview (optional):

1. Add a web user control to your website project.

imageUploadControl.ascx

 

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="imageUploadControl.ascx.cs"
    Inherits="admin_Controls_imageUploadControl" %>
<table>
    <tr>
        <td colspan="3">
            <asp:Label ID="lblMessage" runat="server" Font-Bold="True" CssClass="error"></asp:Label>
        </td>
    </tr>
    <tr>
        <td colspan="3">
            <asp:Image ID="imgUploaded" runat="server" ImageAlign="Middle" Visible="False" />
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="lblImageName" runat="server" Font-Bold="True"></asp:Label>
        </td>
        <td style="width: 230px;">
            <asp:FileUpload ID="imageUpload" runat="server" CssClass="regTextbox" Width="220px" />
        </td>
        <td>
            <asp:CheckBox ID="chkPreview" runat="server" Text="Preview" />
            <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload"
                Width="68px" CssClass="actionButton" />
        </td>
    </tr>
</table>

 

2. Write code for this in code behind file.

imageUploadControl.ascx.cs

 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.IO;

using System.ComponentModel;

//[DefaultBindingProperty("ImageName")]

public partial class admin_Controls_imageUploadControl : System.Web.UI.UserControl
{

    private bool _showPreview;

    public bool ShowPreview
    {

        get { return _showPreview; }

        set { _showPreview = value; }

    }

    private int _height = 100;

    public int Height
    {

        get { return _height; }

        set { _height = value; }

    }

    private int _width = 100;

    public int Width
    {

        get { return _width; }

        set { _width = value; }

    }

    [DefaultValue(""), Localizable(true), Bindable(true, BindingDirection.TwoWay), Category("Behavior")]

    public string ImageName
    {

        get { return lblImageName.Text; }

        set { lblImageName.Text = value; }

    }

    private string _uploadFolder = "CatalogImages/ProductImages";

    public string ImageUploadFolder
    {

        get { return _uploadFolder; }

        set { _uploadFolder = value; }

    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Page_PreRender(object sender, EventArgs e)
    {

        if (ShowPreview)
        {

            imgUploaded.Visible = true;

            imgUploaded.ImageUrl = "~/" + ImageUploadFolder + "/" + ImageName;

            imgUploaded.Height = Unit.Pixel(Height);

            imageUpload.Width = Unit.Pixel(Width);

        }



    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {

        if (chkPreview.Checked)

            _showPreview = true;

        else

            _showPreview = false;

        //

        bool isValidFile = false;

        string fileName = "";

        string localfilepath = "";

        string uploadPath = Server.MapPath("~/" + ImageUploadFolder);

        string uploadFileName = "";

        if (imageUpload.HasFile)
        {

            localfilepath = imageUpload.FileName;

            fileName = Path.GetFileName(localfilepath);

            isValidFile = isFileAllowed(Path.GetExtension(localfilepath));

        }

        if (isValidFile)//now start file upload process
        {

            //check if file already exist and get a uniq upload file name

            uploadFileName = GetUniqueUploadFileName(uploadPath, fileName);

            try
            {

                imageUpload.SaveAs(uploadFileName);

                if (ShowPreview)
                {

                    lblImageName.Text = Path.GetFileName(uploadFileName);

                    imgUploaded.Visible = true;

                    imgUploaded.ImageUrl = "~/" + ImageUploadFolder + "/" + lblImageName.Text;

                    imgUploaded.Height = Unit.Pixel(Height);

                    imageUpload.Width = Unit.Pixel(Width);

                }

                else
                {

                    lblImageName.Text = Path.GetFileName(uploadFileName);

                    imgUploaded.Visible = false;

                }

                lblMessage.Text = "File uploaded.";

            }

            catch (Exception ex)
            {

                lblMessage.Text = ex.Message;

            }

        }

        else
        {

            lblMessage.Text = "Invalid file. Please check extension.";

        }

    }

    private bool isFileAllowed(string fileExtension)
    {

        string[] allowedExtension = { ".jpg", ".gif", ".png" };

        bool allowed = false;

        foreach (string ext in allowedExtension)
        {

            if (ext == fileExtension.ToLower())
            {

                allowed = true;

                break;

            }

        }

        return allowed;

    }

    private string GetUniqueUploadFileName(string uploadPath, string fileName)
    {

        string filepath = uploadPath + "/" + fileName;

        string fileext = Path.GetExtension(filepath);

        string filenamewithoutext = Path.GetFileNameWithoutExtension(filepath);

        do
        {

            Random rnd = new Random();

            int temp = rnd.Next(1000, 1000000);

            filenamewithoutext += "_" + temp;

            fileName = filenamewithoutext + fileext;

            filepath = uploadPath + "/" + fileName;

        } while (File.Exists(filepath));

        return filepath;

    }

}

 

3. Using above control in a page.

 

<%@ Register Src="imageUploadControl.ascx" TagName="imageUploadControl" TagPrefix="uc1" %>

<br />

<table width="800" align="center">



    <tr>



        <td class="regTd1" style="width: 545px">

            <uc1:imageUploadControl ImageUploadFolder="CatalogImages/CategoryImages" ID="ImageUploadControl1" runat="server" />

        </td>

    </tr>

</table>

 

 

That's all easy stuff. Now you can use this control by just dragging and dropping on any page.

Further you can make modification to this control to read configuration values such as UploadPath/Allowed Image Extensionfrom web.config file.

Please feel free to use this code for your need and modify as per your need. If you find any bug please comment I will try to fix this and update.

blog comments powered by Disqus

Posts By Month