Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to upload file in folder and save file path in database using ASP.NET

Author: Rachel Nicole
Download Source Code : 1411_SaveFilePathInDatabase.zip

The purpose of this article is to explain how we can upload file in folder and save uploaded file path in database.

 

Files can be saved in a folder on your Server or you can store files in database in a binary format. When you save file in a folder, you can save file path in database. This approach is better than saving files in database because most of the times you don’t have enough space available in database to save huge number of files. This approach is also easy to implemen.
 
I have created a database and a table for this article. Primary Key of the table is ID and it is auto increment so that it will be automatically generated for every record entry of file. I will store file name, file size and file path in the table. Images and documents will be separately stored in Images and Documents folders under Files folder of my website.
 
 
  1. Open Visual Studio 2010
  2. File > New > Web Site
  3. Visual Basic or Visual C# > ASP.NET Empty Web Site
  4. Right click on web site > Add New Item > Web Form
  5. Right click on website > New Folder. Rename the folder as “Files”.
  6. Right click on Files Folder > New Folder. Rename the folder as “Images”.
  7. Right click on Files Folder > New Folder. Rename the folder as “Documents”.
  8. Write code below in Default.aspx page or Drag and drop following controls

    A FileUpload Control
    A Button Control
    A Label Control

    <asp:FileUpload ID="FileUpload1" runat="server" />
    <br />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload and Save Path in Database" />
    <br />
    <asp:Label ID="Label1" runat="server"></asp:Label>
     
  9. Don’t forget to include following namespaces in code behind file

    VB.NET
     
    Imports System.IO
    Imports System.Data
    Imports System.Data.SqlClient
     
    C#
     
    using System.IO;
    using System.Data;
    using System.Data.SqlClient;
     
  10. Write below function to save file path in database

    VB.NET
     
    Public Sub SaveFilePath(name As String, size As Integer, path As String)
        Dim insertText As String = "INSERT INTO Files(FileName, FileSize, FilePath) VALUES (@FileName, @FileSize, @FilePath)"
        Dim myConnection As String = "Data Source=Local;Initial Catalog=FilesDatabase;Integrated Security=True"
        Dim connection As New SqlConnection(myConnection)
     
        Dim command As New SqlCommand(insertText, connection)
        command.Parameters.Add("@FileName", SqlDbType.VarChar, 50)
        command.Parameters("@FileName").Value = name
        command.Parameters.Add("@FileSize", SqlDbType.Int)
        command.Parameters("@FileSize").Value = size
        command.Parameters.Add("@FilePath", SqlDbType.VarChar, 300)
        command.Parameters("@FilePath").Value = path
        Try
            connection.Open()
            command.ExecuteNonQuery()
       Catch ex As Exception
            Label1.Text = "Unable to insert file data in database"
        Finally
            connection.Close()
        End Try
    End Sub
     
    C#
     
    public void SaveFilePath(string name, int size, string path)
    {
        string insertText = "INSERT INTO Files(FileName, FileSize, FilePath) VALUES (@FileName, @FileSize, @FilePath)";
        string myConnection = "Data Source=Local;Initial Catalog=FilesDatabase;Integrated Security=True";
        SqlConnection connection = new SqlConnection(myConnection);
     
        SqlCommand command = new SqlCommand(insertText, connection);
        command.Parameters.Add("@FileName", SqlDbType.VarChar, 50);
        command.Parameters["@FileName"].Value = name;
        command.Parameters.Add("@FileSize", SqlDbType.Int);
        command.Parameters["@FileSize"].Value = size;
        command.Parameters.Add("@FilePath", SqlDbType.VarChar, 300);
        command.Parameters["@FilePath"].Value = path;
        try
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Label1.Text = "Unable to insert file data in database";
        }
        finally
        {
            connection.Close();
        }
    }
     
     
    Here is the explanation of the code.
     
    Above function insert file name, size and path to database
    I have written insert statement with column names and values.
    I have to connect to the Server to save data.
    Then I have created the SqlCommand object and add all three parameters to it with values.
    In try block, I have opened the connection to the server and called the ExecuteNonQuery().
    In “Catch” block I have displayed a message in case of any error.
     
  11. Write code below in button click event

    VB.NET

    Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        Dim correctExtension As Boolean = False
     
        If FileUpload1.HasFile Then
            Dim fileName As String = FileUpload1.PostedFile.FileName
            Dim fileSize As Integer = FileUpload1.PostedFile.ContentLength
            Dim fileExtension As String = Path.GetExtension(fileName).ToLower()
     
            Dim extensionsAllowed As String() = {".doc", ".docx", ".xls", ".xlsx", ".txt", ".jpg", ".png"}
     
            If extensionsAllowed.Contains(fileExtension) Then
                correctExtension = True
            End If
     
            If correctExtension Then
                If fileExtension = ".docx" OrElse fileExtension = ".txt" OrElse fileExtension = ".xlsx" Then
                   Try
                        Dim filePath As String = Server.MapPath("~/Files/Documents/" + fileName)
                        FileUpload1.PostedFile.SaveAs(filePath)
                        SaveFilePath(fileName, fileSize, filePath)
                        Label1.Text = "File successfully uploaded and file path saved in database"
                    Catch ex As Exception
                        Label1.Text = "Unable to upload file"
                    End Try
                ElseIf fileExtension = ".jpg" OrElse fileExtension = ".png" Then
                    Try
                        Dim filePath As String = Server.MapPath("~/Files/Images/" + fileName)
                        FileUpload1.PostedFile.SaveAs(filePath)
                        SaveFilePath(fileName, fileSize, filePath)
                        Label1.Text = "File successfully uploaded and file path saved in database"
                    Catch ex As Exception
                        Label1.Text = "Unable to upload file"
                    End Try
     
                End If
            Else
                Label1.Text = "File extension " + fileExtension + " is not allowed"
            End If
        End If
    End Sub
     
    C#
     
    protected void Button1_Click(object sender, EventArgs e)
    {
        bool correctExtension = false;
     
        if (FileUpload1.HasFile)
        {
            string fileName = FileUpload1.PostedFile.FileName;
            int fileSize = FileUpload1.PostedFile.ContentLength;
            string fileExtension = Path.GetExtension(fileName).ToLower();
     
            string[] extensionsAllowed = { ".doc", ".docx", ".xls", ".xlsx", ".txt", ".jpg", ".png" };
     
            if (extensionsAllowed.Contains(fileExtension))
            {
                correctExtension = true;
            }
     
            if (correctExtension)
            {
                if (fileExtension == ".docx" || fileExtension == ".txt" || fileExtension == ".xlsx")
                {
                    try
                    {
                        string filePath = Server.MapPath("~/Files/Documents/" + fileName);
                        FileUpload1.PostedFile.SaveAs(filePath);
                        SaveFilePath(fileName, fileSize, filePath);
                        Label1.Text = "File successfully uploaded and file path saved in database";
                    }
                    catch (Exception ex)
                    {
                        Label1.Text = "Unable to upload file";
                    }
                }
                else if (fileExtension == ".jpg" || fileExtension == ".png")
                {
                    try
                    {
                        string filePath = Server.MapPath("~/Files/Images/" + fileName);
                        FileUpload1.PostedFile.SaveAs(filePath);
                        SaveFilePath(fileName, fileSize, filePath);
                        Label1.Text = "File successfully uploaded and file path saved in database";
                    }
                    catch (Exception ex)
                    {
                        Label1.Text = "Unable to upload file";
                    }
                }               
            }
            else
            {
                Label1.Text = "File extension " + fileExtension + " is not allowed";
            }
        }
    }
     
    Here is the explanation of the code in button click event.
     
    At the start of the “Button1_Click” method, I have declared a variable “correctExtension” and initializing it to “False”. It is used in the code to check the correct extension of the file which will be uploaded.
    In “If” statement expression, I have used the “HasFile” property of the “FileUpload” to check that “FileUpload” Control contains the file to upload.
    “FileName” property of “PostedFile” (Which is property of “FileUpload”) is used to get the name of the file and assigned this name to a “String” variable.
    “ContentLength” property of “PostedFile” (Which is property of “FileUpload”) is used to get the size of the file and assigned this type to a integer variable.
    Then I have another “String” variable to store the extension of the file. “Path” class has the “GetExtension()” method which takes the file name and returns the extension of that file. I have used “ToLower()” method to convert the extension into lower case.
    Next I have declared an “Array” of “Strings” (named extensionsAllowed) to store extensions which I want for files to be uploaded and initialized it with six file extensions.
    I have used Contains() method of “extensionsAllowed” array by providing fileExtension to check that the extension of the file exists in the allowed  
    Then there is another “If” statement to check “fileExtension”. If it is word, excel or text file then in try block, I have set the file path by using Server.MapPath().
    Then I have called the SaveAs() method to save file in the specified “Document” folder in “Files” folder. Then I have called the SaveFilePath() method by providing all parameters.
    On the other hand, if “fileExtension” is of type image then I have changed the file path and set “Images” folder in “Files” folder. SaveFilePath method is called here also for saving image file path in database.
    At the end, I am displaying message that the file uploaded and path saved in database.
    In “Catch” block I have displayed a message in case of any error.

  12. Right Click on website > View web site in browser.

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to hide GridView column and retrieve value from hidden column cell in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net