Loading ...

File upload with validation in ASP.NET | CodeAsp.Net

File upload with validation in ASP.NET

 /5
0 (0votes)

In this blog I will explain how to upload some particular file upload in ASP.NET.


In below code there is a fileupload (fuTest) and a button (btnUpload) control.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td><asp:FileUpload ID="fuTest" runat="server" />
                
                <%--with the below RegularExpressionValidator user can upload only JPG 
                and TEXT file. If you want user can more upload file you can modify 
                regular expression. Example - User can upload DOC and PDF
                file, you will use "jpg|JPG|txt|TXT|doc|DOC|pdf|PDF"  
                regular expression.--%>
                <asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" 
                ErrorMessage="Only jpg, txt file are allowed!" 
                ValidationExpression="^.*\.(jpg|JPG|txt|TXT)$" 
                 ControlToValidate="fuTest"></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                 <td><asp:Button ID="btnUpload" runat="server" Text="Upload" 
                         onclick="btnUpload_Click" /></td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

using System;
using System.Web;


public partial class FileUploadCntrl : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //HttpPostedFile use to select and upload files from a client.
        HttpPostedFile file = (HttpPostedFile)(fuTest.PostedFile);

        //getting file size
        int fileSize = file.ContentLength;

        //checking file size is it greater than 10485760 byets or not
        //10MB = 10*1024(KB)*1024(byte)
        //so 10MB is equal to 10485760 bytes
        if(fileSize>10485760)
        {
            Response.Write("file is heavy");
        }
        else
        {
            //save file in below path
            fuTest.SaveAs("D:\\" + fuTest.FileName);
        }
        
    }
}

In web.config file You can set maximum size of file that can be uploaded . The default limit size
is around 4 MB. But you can modify the limit; you have to change in web.config file.

Example – you want to upload around 10MB you can write below code in web.config
file (in system.web section):-

<httpRuntime maxRequestLength="10240" executionTimeout="300"/> 


Happy Coding:)

Comments (1)

   
hajan
Hah easy and nice! I like it! I don't use iframes a lot in nowadays, but this definitely seems lovely
7/13/2010
 · 
by

Top Posts