Saturday, October 2, 2010

ASP.net - File upload control in asp.net

The FileUpLoad control enables you to upload file to the server. It displays a text box control and a browse button that allow users to select a file to upload to the server.

Let see how to upload file into a server.

Step 1
Create a web application and give solution name as SolFileUpload.

Step 2
Add a fileupload control,button control and lable control on page,it is look like this


<asp:ScriptManager ID="ScriptManager1" runat="server">
       </asp:ScriptManager>  

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">

            <ContentTemplate>
                <asp:FileUpload ID="FileUpload1" runat="server" />
                <br />

                <asp:Button ID="btnUpload" runat="server" Text="Upload" 
                    onclick="btnUpload_Click"  />
                </br>
                
                <asp:Label ID="lblStatus" runat="server"></asp:Label>
                </br>   
            </ContentTemplate>    

            <Triggers>
                <asp:PostBackTrigger ControlID="btnUpload" /> 
            </Triggers>   

        </asp:UpdatePanel>  

Step 3
Add a file extensions in web.config file for validate file extension,it is look like this

<appSettings>
    <add key ="Extension" value =".gif,.png,.jpeg,.jpg"/>
  </appSettings>

Step 4
Create a FileExtensionChecker static class in App_Code folder,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;


public static class FileExtensionChecker
{

    #region private Property

    /// <summary>
    /// Get the extension from web.config
    /// </summary>
    private static String[] GetExtension
    {
        get
        {
            String GetRawExt = System.Configuration.ConfigurationManager.AppSettings["Extension"];

            String[] SplitExt = System.Text.RegularExpressions.Regex.Split(GetRawExt, ",");

            return SplitExt; 
        }
    }
   

    #endregion

    #region Public Methods
    /// <summary>
    /// check file extension 
    /// </summary>
    /// <param name="FileName">Specify the file name</param>
    /// <returns>Boolean</returns>
    public static Boolean CheckFileExtension(String FileName)
    {
        Boolean Flag = false; 
        try
        {
            String FileExtension = System.IO.Path.GetExtension(FileName).ToLower();

            for (int i = 0; i < GetExtension.Length; i++)
            {
                if (FileExtension == GetExtension[i])
                {
                    Flag = true;
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
        return Flag; 
    }

    #endregion
}

GetExtension Property
get the extensions from web.config file and store in a array of string.

CheckFileExtension Method
If a given file extension is match with which stored in web.config file extension then it will return true otherwise it will return false.
Step 5
Write a FileUploadToServer() method in default class[Default.aspx.cs] for upload image in UploadedImages folder in solution. first you have to create a uploadedimages folder in solution
it is look like this

  #region Methods
    /// <summary>
    /// File upload to the server.
    /// </summary>
    private void FileUploadToServer()
    {
        try
        {
            String FullPath = Server.MapPath("~/UploadedImages/");

            if (FileUpload1.HasFile)
            {
               
                if (FileExtensionChecker.CheckFileExtension(FileUpload1.FileName)== true)
                {
                    try
                    {
                        FileUpload1.PostedFile.SaveAs(FullPath + FileUpload1.FileName);
                        lblStatus.Text = "File uploaded.";
                    }
                    catch (Exception)
                    {
                        lblStatus.Text = "File could not be uploaded.";
                    }

                }
                else
                {
                    lblStatus.Text = "Cannot accept files of this type.";
                }
                
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    #endregion

Step 6
Call FileUploadToServer() method on button click event,it is look like this

 protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            FileUploadToServer();
        }
        catch (Exception)
        {
        }
    }

Full Code

1. .aspx Code

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>

<body>
    <form id="form1" runat="server">
   
    <div>
       
       <asp:ScriptManager ID="ScriptManager1" runat="server">
       </asp:ScriptManager>  

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">

            <ContentTemplate>
                <asp:FileUpload ID="FileUpload1" runat="server" />
                <br />

                <asp:Button ID="btnUpload" runat="server" Text="Upload" 
                    onclick="btnUpload_Click"  />
                </br>
                
                <asp:Label ID="lblStatus" runat="server"></asp:Label>
                </br>   
            </ContentTemplate>    

            <Triggers>
                <asp:PostBackTrigger ControlID="btnUpload" /> 
            </Triggers>   

        </asp:UpdatePanel>  

    </div>
    </form>
</body>
</html>

2. .aspx.cs [Code behind]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
          
        }
        catch (Exception)
        { }
    }

    #region Methods
    /// <summary>
    /// File upload to the server.
    /// </summary>
    private void FileUploadToServer()
    {
        try
        {
            String FullPath = Server.MapPath("~/UploadedImages/");

            if (FileUpload1.HasFile)
            {
               
                if (FileExtensionChecker.CheckFileExtension(FileUpload1.FileName)== true)
                {
                    try
                    {
                        FileUpload1.PostedFile.SaveAs(FullPath + FileUpload1.FileName);
                        lblStatus.Text = "File uploaded.";
                    }
                    catch (Exception)
                    {
                        lblStatus.Text = "File could not be uploaded.";
                    }

                }
                else
                {
                    lblStatus.Text = "Cannot accept files of this type.";
                }
                
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    #endregion
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            FileUploadToServer();
        }
        catch (Exception)
        {
        }
    }
  
}

Run the project.

Download
Download Source Code

No comments:

Post a Comment