Home > Articles > ASP.NET Articles > How to upload a file to web server in asp.net and store file path into database table?

How to upload a file to web server in asp.net and store file path into database table?

by Thamil   on Jul 02, 2013   Category: ASP.NET  | Level: Intermediate  |  Views: 60878    |  Points: 100   
Like this article? Bookmark and Share:
This article describe how to upload a file into web server folder using asp.net file upload control and store the file information into sql server database.

Introduction


In general, uploading a file into web server is common requirement in asp.net project using file upload control. It’s easy and simple to use file upload control, see the below steps 

Step1: Create Asp.net project


First create asp.net project and add aspx page then drag the file upload control into aspx page. Configure the path in the web.config file where we need to upload/store file in the web server and prepare the database connection string and configure in connectionstring section. Once we upload the file into web server then store the file information and path in database and display with gridview control.  See the below layout of aspx page.


Step2: File upload page layout


Copy the below code and place into aspx page. In the below page we have file upload control to upload file and gridview control to display the uploded file details from database.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="File_upload._Default" %>
<!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>Demo File Upload control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color: #0066FF; font-weight: bold;">
            <u>File Upload</u></h2>
    </div>
    <div>
        <asp:FileUpload ID="FileUploadToServer" Width="300px" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click"
            ValidationGroup="vg" /><br />
        <br />
        <asp:Label ID="lblMsg" runat="server" ForeColor="Green" Text=""></asp:Label>
        <br />
        <h2 style="text-decoration: underline; font-weight: bold; color: #0066FF;">
            Uploaded File Details
        </h2>
        <asp:GridView ID="GridViewUploadedFile" runat="server" EmptyDataText="No files found!"
            AutoGenerateColumns="False" Font-Names="Verdana" AllowPaging="true" PageSize="5"
            Width="50%" OnPageIndexChanging="GridViewUploadedFile_PageIndexChanging" BorderColor="#CCCCCC"
            BorderStyle="Solid" BorderWidth="1px">
            <AlternatingRowStyle BackColor="#FFD4BA" />
            <HeaderStyle Height="30px" BackColor="#FF9E66" Font-Size="15px" BorderColor="#CCCCCC"
                BorderStyle="Solid" BorderWidth="1px" />
            <RowStyle Height="20px" Font-Size="13px" BorderColor="#CCCCCC" BorderStyle="Solid"
                BorderWidth="1px" />
            <Columns>
                <asp:BoundField DataField="rowid" HeaderText="#" HeaderStyle-Width="10%" />
                <asp:TemplateField HeaderText="List of Files" HeaderStyle-Width="90%">
                    <ItemTemplate>
                        <asp:HyperLink ID="HyperLink1" Target="_blank" runat="server" Text='<%# Eval("filenameName") %>'
                            NavigateUrl='<%# Eval("filePath") %>'>
                        </asp:HyperLink>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
 

Page look like as shown below

 

Step3: Code behind part


Take below code and place into code behind file.

Namespace used:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web.UI.WebControls;

     1. Page load: Display the uploaded file information when page loads, The loadData() function used to retreive records using sql server stored procedure. I have attached database table structure and stored procedure script with this article.

        string strCon = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlDataAdapter SqlAda;
        DataSet ds;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }
        private void LoadData()
        {
            using (SqlConnection Sqlcon = new SqlConnection(strCon))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    Sqlcon.Open();
                    cmd.Connection = Sqlcon;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "SP_FileUpload";
                    cmd.Parameters.Add(new SqlParameter("@pvchAction", SqlDbType.VarChar, 50));
                    cmd.Parameters["@pvchAction"].Value = "select";
                    cmd.Parameters.Add("@pIntErrDescOut", SqlDbType.Int).Direction = ParameterDirection.Output;
                    SqlAda = new SqlDataAdapter(cmd);
                    ds = new DataSet();
                    SqlAda.Fill(ds);
                    GridViewUploadedFile.DataSource = ds;
                    GridViewUploadedFile.DataBind();
                }
            }
        }

     2. btnUpload_Click event: In this event, we are store/save the file into specified path before that we have few validation such as file size verification, file extension and whether user selected the file or not before upload clicked.

 protected void btnUpload_Click(object sender, EventArgs e)
        {
            //Get path from web.config file to upload
            string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
            bool blSucces = false;
            string filename = string.Empty;
            //To check whether file is selected or not to uplaod
            if (FileUploadToServer.HasFile)
            {
                try
                {
                    string[] allowdFile = { ".pdf" };
                    //Here we are allowing only pdf file so verifying selected file pdf or not
                    string FileExt = System.IO.Path.GetExtension(FileUploadToServer.PostedFile.FileName);
                    bool isValidFile = allowdFile.Contains(FileExt);
                    if (!isValidFile)
                    {
                        lblMsg.ForeColor = System.Drawing.Color.Red;
                        lblMsg.Text = "Please upload only pdf ";
                    }
                    else
                    {
                        // Get size of uploaded file, here restricting size of file
                        int FileSize = FileUploadToServer.PostedFile.ContentLength;
                        if (FileSize <= 1048576)//1048576 byte = 1MB
                        {
                            //Get file name of selected file
                            filename = Path.GetFileName(FileUploadToServer.FileName);
                            //Save selected file into specified location
                            FileUploadToServer.SaveAs(Server.MapPath(FilePath) + filename);
                            lblMsg.Text = "File upload successfully!";
                            blSucces = true;
                        }
                        else
                        {
                            lblMsg.Text = "Attachment file size should not be greater then 1 MB!";
                        }
                    }
                }
                catch (Exception ex)
                {
                    lblMsg.Text = "Error occurred while uploading a file: " + ex.Message;
                }
            }
            else
            {
                lblMsg.Text ="Please select a file to upload.";
            }
            //Store file details into database
            if (blSucces)
            {
                Updatefileinfo(filename, FilePath + filename);
            }
        }
        private void Updatefileinfo(string strfilename, string strPath)
        {
            using (SqlConnection Sqlcon = new SqlConnection(strCon))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    Sqlcon.Open();
                    cmd.Connection = Sqlcon;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "SP_FileUpload";
                    cmd.Parameters.Add(new SqlParameter("@pvchAction", SqlDbType.VarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@pvchFileName", SqlDbType.VarChar, 100));
                    cmd.Parameters.Add(new SqlParameter("@pvchFilepath", SqlDbType.VarChar, 100));
                    cmd.Parameters.Add(new SqlParameter("@pvchCreatedBy", SqlDbType.VarChar, 100));
                    cmd.Parameters.Add("@pIntErrDescOut", SqlDbType.Int).Direction = ParameterDirection.Output;
                    cmd.Parameters["@pvchAction"].Value = "insert";
                    cmd.Parameters["@pvchFileName"].Value = strfilename;
                    cmd.Parameters["@pvchFilepath"].Value = strPath;
                    cmd.Parameters["@pvchCreatedBy"].Value = "Admin";
                    cmd.ExecuteNonQuery();
                    int retVal = (int)cmd.Parameters["@pIntErrDescOut"].Value;
                }
            }
            //Display complete uploaded file details in gridview
            LoadData();
        }

    3. gridview PageIndexChanging: This event used to navigate page in gridview control.

protected void GridViewUploadedFile_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridViewUploadedFile.PageIndex = e.NewPageIndex;
            LoadData();
        }

 

So now we have stored some pdf files into web server folder and saved file path and name into database and displayed in gridview. Added hyperlink in itemTemplate to open file directly from folder. See the below screen shot to open uploaded pdf file from server.

So once we move this build into server, we need provide the folder permission to upload files. So add “Network service” for specific folder and allow Read & execute, List folder contents, Read and write permissions.

By default, we can upload files into web server upto 4 mb file size. If you want to upload more then 4mb we need to change the maxRequestLength parameter under httpRuntime section in machine.config file.

I have attached sample project and database script. Attachment will have below items

  1. Database script: execute the script in your test database
  2. Demo project: Open project and change DB connection string in web.config file
  3. Run project.

I hope you enjoyed this article and provide your feedback and suggestions.



Like this article? Bookmark and Share:

Most viewed Articles

User Comments


No response found, be the first to review this article.

Submit feedback about this article

Please sign in to post feedback

Latest Posts