File Upload Control in ASP.NET

FileUpload.aspx

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

<!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>Upload Image</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        &nbsp;
        <asp:Button ID="btnUpload" runat="server" Text="Upload" 
            onclick="btnUpload_Click" />
        <br />
        <br />
        <br />
        <asp:Image ID="imgViewr" runat="server" />
        <span id="spnMessage" runat="server"></span>
    </div>
    </form>
</body>
</html>


FileUpload.cs

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class FileUpload : System.Web.UI.Page
{
    public string strImagePath ="~/Images/";    
    public System.Collections.Generic.List<string> arrValidExtention = new System.Collections.Generic.List<string>();
    protected void Page_Load(object sender, EventArgs e)
    {
        arrValidExtention.Add(".JPG");
        arrValidExtention.Add(".JPEG");        
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {   
        //Check file is selected or not
        if (FileUpload1.PostedFile.FileName != "")
        {
            try {
                //Get selected file extention
                string strFileExtention = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName).ToUpper();
                //if (strFileExtention == ".jpg".ToUpper() || strFileExtention == ".jpeg".ToUpper())                 
                
                if (arrValidExtention.Contains(strFileExtention))                
                {
                    //Save selected file
                    FileUpload1.PostedFile.SaveAs(Server.MapPath(strImagePath + FileUpload1.PostedFile.FileName));
                    spnMessage.InnerText = "File uploaded successfully.";
                }
                else
                {
                    spnMessage.InnerText = "Please select JPEG|JPG file.";
                }
            }
            catch (Exception exp)
            {
                spnMessage.InnerText = exp.Message.ToString();
            }
        }
    }

    
}



Ebook Download
View all
Learn
View all