Nov 24, 2011

Upload file on fileUpload onchange event in asp.net



==================== ASPX code======================
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        <asp:FileUpload ID="FileUpload1" onchange="if (confirm('Upload ' + this.value + '?')) this.form.submit();" runat="server" />      
            <br />

<asp:RegularExpressionValidator ID="rexp" runat="server" ControlToValidate="FileUpload1"
     ErrorMessage="Only .DAT,.PNG,.BMP,.JPEG,.XLSX,.DOCX,.PPTX,
.DXF,.DRW,.SLD,.TXT,.PPT,.XLS,.PPS,.DOC,
.PDF,.GIF,.JPG,.RTF"
     ValidationExpression="(.*\.([Gg][Ii][Ff])|.*\.([Jj][Pp][Gg])|.*\.([Bb][Mm][Pp])|.*\.([pP][nN][gG])|.*\.([xX][lL][sS][xX])|.*\.([dD][oO][cC][xX])|.*\.([pP][pP][tT][xX])|.*\.([dD][xX][fF])|.*\.([dD][rR][wW])|.*\.([sS][lL][dD])|.*\.([tT][xX][tT])|.*\.([pP][pP][tT])|.*\.([xX][lL][sS])|.*\.([pP][pP][sS])|.*\.([dD][oO][cC])|.*\.([pP][dD][fF])|.*\.([dD][aA][tT])|.*\.([rR][tT][fF])$)"></asp:RegularExpressionValidator>


            <asp:Label ID="lblFileSize" runat="server" Text="Label"></asp:Label></div>
    </form>
</body>
</html>
==================================================

====================On page Load======================
protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            if (FileUpload1.HasFile)
            {
                string strFileName, strFileExtension;
                strFileName = FileUpload1.FileName;
                strFileExtension = strFileName.Substring(strFileName.LastIndexOf('.') + 1);
                lblFileSize.Text = FileUpload1.PostedFile.ContentLength.ToString();
                string strSavedFilePath = Server.MapPath("~//CTD_Files");
                strFileName = strFileName.Substring(0, strFileName.LastIndexOf('.')) + DateTime.Now.ToString("ddMMyyyyhhmmss") + "." + strFileExtension.Trim();
                strSavedFilePath += "\\" + strFileName;
                FileUpload1.PostedFile.SaveAs(strSavedFilePath);
            }
        }
    }

====================================================

No comments:

Post a Comment

What is the use of n-tier architecture and 3-tier architecture?

how to implement 3-tier architecture in asp.net using c#. 3-Tier architecture is also called layered architecture. Some people called it ...