.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

File Upload Control in ASP.Net with Codings

Posted By:Prasanti Prusty       Posted Date: December 18, 2009    Points: 25    Category: ASP.NET    URL: http://www.dotnetspark.com  
 

Introduction

ASP.Net 2.0 comes up with a new control "File Upload" , which used to accepting file uploads from users.
Using this control the process has become extremely easy.
With the FileUpload control, it can be done with a small amount of code lines,
Here is the markup required to upload the File:

   
   
   


   

Settings To be done :

In "web.config" set the following for size of the File allowed.
To allow file size larger than default Size (4MB) & to change "executionTimeout",
need to set "maxRequestLength" value in KB and "executionTimeout" value in sec as follows:

    


CodeBehind for upload:

Once the UploadButton is clicked, we need to check if a file has been specified in the upload control.
If it has, we use the FileUpload controls SaveAs method to save the file.  

Here we use the properties ContentLength to do some basic checking of the file which the user is trying to upload.

This Code Validates for the followings.

   1. Only .doc, .docx, .ppt, .pptx, .xls, .xlsx, .pdf, .zip, .rtf, .jpg, .jpeg, .gif files can be Uploaded.
   2. Filename must not exceed 100 characters (including extension).
   3. Total Size of file (per Upload) must not exceed 10 MB.

Codings :
Imports System.IO
Imports System.Data.SqlClient

Partial Class FileUpload
    Inherits System.Web.UI.Page

#Region "Variables"
    Dim con As New SqlConnection
    Dim com As New SqlCommand
    Dim upldirinfo As DirectoryInfo
#End Region

#Region "Click on Upload"
    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        Try
            If Page.IsValid Then
                If ServerValidation() Then
                    Dim strftpPath1 As String = "C:\UploadFiles"
                    If FileUpload1.FileName.ToString <> "" Then

                        If strftpPath1 <> "" Then
                            upldirinfo = New DirectoryInfo(strftpPath1)
                            If Not upldirinfo.Exists Then
                                upldirinfo.Create()
                            End If
                            Dim filename As String = FileUpload1.PostedFile.FileName
                            filename = filename.Remove(0, filename.LastIndexOf("\") + 1)
                            Dim filpath As String = strftpPath1 + "\" + filename
                            Dim filinfo As FileInfo
                            filinfo = New FileInfo(filpath)
                            If Not filinfo.Exists Then
                                FileUpload1.PostedFile.SaveAs(strftpPath1 + "\" + filename)
                                ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "")
                                'DB Connection to Save the Deatils in Backend.
                               
con.ConnectionString = "Password=SSSS;Persist Security Info=True;User
ID=SSSSSS;Initial Catalog=SSSSSSS;Data Source=SSSSSSSSS"
                                con.Open()
                                com.Connection = con
                                com.CommandType = Data.CommandType.Text
                               
com.CommandText = "INSERT INTO tbFileUpload VALUES('" & strftpPath1
& "','" & filename & "')"
                                com.ExecuteNonQuery()
                            Else
                                ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "")
                            End If
                        Else
                            ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "")
                        End If
                    Else
                        ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "")
                    End If
                End If
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
#End Region

#Region "Code for ServerValidation"
    Public Function ServerValidation() As Boolean
        Try
            Dim size, intlen As Long 'Uploaded File Size
            Dim strExt1 As String 'Extension Type
            Dim retVal As Int16
            size = FileUpload1.PostedFile.ContentLength
            intlen = FileUpload1.FileName.LastIndexOf("\")
            retVal = FileUpload1.FileName.Substring(intlen + 1, FileUpload1.FileName.Length - intlen - 1).Length
            'getting uploaded file Extension Type
            If FileUpload1.HasFile Then
                Dim strArr As String() = FileUpload1.FileName.Split(".")
                strExt1 = strArr(strArr.Length - 1).ToLower
            End If

            'Checking Validation
            If Not FileUpload1.HasFile Then
                ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "")
                Return False
            ElseIf (FileUpload1.HasFile And FileUpload1.FileName.LastIndexOf(".") = -1) Then
                ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "")
                SetFocus(FileUpload1)
                Return False
           
ElseIf strExt1 <> "doc" And strExt1 <> "docx" And strExt1
<> "xls" And strExt1 <> "xlsx" And strExt1 <> "ppt"
And strExt1 <> "pptx" And strExt1 <> "pdf" And strExt1
<> "zip" And strExt1 <> "rtf" And strExt1 <> "jpg"
And strExt1 <> "jpeg" And strExt1 <> "gif" And strExt1
<> "" Then
                ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "")
                SetFocus(FileUpload1)
                Return False
            ElseIf retVal > 100 Then
                ' To Check File Name Length (100chars)
                ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "")
                Return False
            ElseIf size > 10240000 Then 'Must not exceed 10 MB.
                ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "")
                Return False
            Else
                Return True
            End If
        Catch ex As Exception
            Return False
            Throw ex
        End Try
    End Function
#End Region

#Region "Code for Clear the Text"
    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        FileUpload1.Visible = True
    End Sub
#End Region

#Region "Code for Close"
    Protected Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
        ClientScript.RegisterStartupScript(Me.GetType(), "onClick", "")
    End Sub
#End Region

End Class


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend