Home Asp.net Upload File to Server Folder for Download in Asp.net using C# Vb.net

Upload File to Server Folder for Download in Asp.net using C# Vb.net

161
0
How to upload files to server folder for download in asp.net c# vb.net?
How to upload files to server folder for download in asp.net c# vb.net?

In my previous tutorials, I’d explained about get files list from directory, how to bind data to gridview, insert update delete gridview data using parameterized query, difference between executereader executenonquery and executescalar and other more cracking tutorials on Files, Asp.net, GridView, jQuery here.

Now here in this tutorial, I’ll explain how to upload the files from your local computer and save it to server folder and then download that files from server folder in asp.net using c# and vb.net with sample demo and example code.

There are lots of plug-ins are available in the market to upload files using jQuery and JavaScript. In that some plug-ins are free and some are premium. I’ll cover that in my later posts but here I’ll explain you how to upload files and save file full path to sql server table for download from gridview using asp.net fileupload control. We need to save path to sql server because later it will be required to get the uploaded files for the download.

To save the file details to sql server we need one table. To create table in your database use this script:

CREATE TABLE [dbo].[FileDetails]
(
    [FileId] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
    [FileName] [nvarchar](50) NULL,
    [FileSize] [nvarchar](50) NULL,
    [FileExtension] [nvarchar](20) NULL,
    [FilePath] [nvarchar](500) NULL
)

After creating database table, check the following HTML Markup and Code-behind code snippets that I prepared for the demonstration.

HTML Markup [.aspx]

Following is the complete HTML Markup code for file upload control of .aspx page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
    <title>Upload and Download files in Asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr>
            <td>
                <asp:FileUpload ID="fuFileUploader" runat="server" />
            </td>
            <td>&nbsp;</td>
            <td>
                <asp:Button ID="btnUploadFiles" runat="server" Text="Upload Me!"
                    OnClick="btnUploadMe_Click" />
            </td>
        </tr>
        <tr>
            <td colspan="3">&nbsp;</td>
        </tr>
        <tr>
            <td colspan="3">
                <asp:GridView ID="gvUploadedFiles" runat="server" AutoGenerateColumns="false"
                    DataKeyNames="FileId">
                    <HeaderStyle Font-Bold="true" BackColor="#ff6600" BorderColor="#f5f5f5"
                        ForeColor="White" Height="30" />
                    <Columns>
                        <asp:BoundField DataField="FileId" HeaderText="#" ControlStyle-Width="50" />
                        <asp:BoundField DataField="FileName" HeaderText="FileName"
                            ControlStyle-Width="250" />
                        <asp:BoundField DataField="FileSize" HeaderText="FileSize"
                            ControlStyle-Width="250" />
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkDownloadMe" runat="server" Text="Download Me!"
                                    OnClick="lnkDownloadMe_Click" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
        <tr>
            <td colspan="3">&nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblMsg" runat="server" ForeColor="Red"></asp:Label>
            </td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>
Note: In this tutorial, I’d not validate file extension during uploading files to server. If you want to validate file extensions before uploading files, check how to validate file extension before upload and preview image before uploading here.

After adding HTML Markup code in your .aspx page, check the below code-behind code in your project language.

File Upload And Download From Gridview Example – [C#]

First add the following namespace:

using System.Data.SqlClient;
using System.IO;

Now add the below sample code snippet to perform upload and download files from server folder:

//specify your connection string here..
string strConn = "Data Source=datasource;Integrated Security=true;Initial Catalog=yourDB";

protected void Page_Load(object sender, EventArgs e) {
    lblMsg.Text = "";
    if (!IsPostBack) {
        BindGridviewFileData();
    }
}

//save file details to database as well as server folder
protected void btnUploadMe_Click(object sender, EventArgs e) {
    try {
        if (fuFileUploader.PostedFile != null && fuFileUploader.PostedFile.ContentLength > 0) {
            string fileName = Path.GetFileName(fuFileUploader.PostedFile.FileName);
            string fileExtension = Path.GetExtension(fuFileUploader.PostedFile.FileName);

            //first check if "uploads" folder exist or not, if not create it
            string fileSavePath = Server.MapPath("uploads");
            if (!Directory.Exists(fileSavePath))
                Directory.CreateDirectory(fileSavePath);

            //after checking or creating folder it's time to save the file
            fileSavePath = fileSavePath + "//" + fileName;
            fuFileUploader.PostedFile.SaveAs(fileSavePath);
            FileInfo fileInfo = new FileInfo(fileSavePath);
            using (SqlConnection sqlConn = new SqlConnection(strConn)) {
                using (SqlCommand sqlCmd = new SqlCommand()) {
                    sqlCmd.CommandText = @"INSERT INTO FileDetails (FileName,FileSize,FileExtension,FilePath)
                                       VALUES (@FileName,@FileSize,@FileExtension,@FilePath);";
                    sqlCmd.Parameters.AddWithValue("@FileName", fileName);
                    sqlCmd.Parameters.AddWithValue("@FileSize", fileInfo.Length.ToString());
                    sqlCmd.Parameters.AddWithValue("@FileExtension", fileExtension);
                    sqlCmd.Parameters.AddWithValue("@FilePath", fileSavePath);
                    sqlCmd.Connection = sqlConn;
                    sqlConn.Open();
                    sqlCmd.ExecuteNonQuery();
                    sqlConn.Close();
                    BindGridviewFileData();
                }
            }

            lblMsg.Text = "File Uploaded Successfully!";
            lblMsg.ForeColor = System.Drawing.Color.Green;
        } else {
            lblMsg.Text = "Error: Please select a file to upload!";
        }
    } catch {
        lblMsg.Text = "Error: Error while uploading file!";
    }
}

//download button to download files from gridview
protected void lnkDownloadMe_Click(object sender, EventArgs e) {
    try {
        LinkButton lnkbtn = sender as LinkButton;
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
        int fileId = Convert.ToInt32(gvUploadedFiles.DataKeys[gvrow.RowIndex].Value.ToString());
        using (SqlConnection sqlConn = new SqlConnection(strConn)) {
            using (SqlCommand sqlCmd = new SqlCommand()) {
                sqlCmd.CommandText = "SELECT * FROM FileDetails WHERE FileId=@FileId";
                sqlCmd.Parameters.AddWithValue("@FileId", fileId);
                sqlCmd.Connection = sqlConn;
                sqlConn.Open();
                SqlDataReader dr = sqlCmd.ExecuteReader();
                if (dr.Read()) {
                    string fileName = dr["FileName"].ToString();
                    string fileLength = dr["FileSize"].ToString();
                    string filePath = dr["FilePath"].ToString();
                    if (File.Exists(filePath)) {
                        Response.Clear();
                        Response.BufferOutput = false;
                        Response.ContentType = "application/octet-stream";
                        Response.AddHeader("Content-Length", fileLength);
                        Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
                        Response.TransmitFile(filePath);
                        Response.Flush();
                    } else {
                        lblMsg.Text = "Error: File not found!";
                    }
                }
            }
        }
    } catch {
        lblMsg.Text = "Error: Error while downloading file!";
    }
}

//bind file details to gridview
private void BindGridviewFileData() {
    try {
        using (SqlConnection sqlConn = new SqlConnection(strConn)) {
            using (SqlCommand sqlCmd = new SqlCommand()) {
                sqlCmd.CommandText = "SELECT * FROM FileDetails";
                sqlCmd.Connection = sqlConn;
                sqlConn.Open();
                gvUploadedFiles.DataSource = sqlCmd.ExecuteReader();
                gvUploadedFiles.DataBind();
                sqlConn.Close();
            }
        }
    } catch { }
}

File Upload And Download From Gridview Example – [Vb.net]

First add the following namespace:

Imports System.Data.SqlClient
Imports System.IO

Now add the below sample code snippet to perform upload and download files from server folder:

'specify your connection string here..'
Dim strConn As String = "Data Source=datasource;Integrated Security=true;Initial Catalog=yourDB"

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    lblMsg.Text = ""
    If Not IsPostBack Then
        BindGridviewFileData()
    End If
End Sub

'save file details to database as well as server folder'
Protected Sub btnUploadMe_Click(ByVal sender As Object, ByVal e As EventArgs)
    Try
        If fuFileUploader.PostedFile IsNot Nothing Then
            Dim fileName As String = Path.GetFileName(fuFileUploader.PostedFile.FileName)
            Dim fileExtension As String = Path.GetExtension(fuFileUploader.PostedFile.FileName)

            'first check if "uploads" folder exist or not, if not create it'
            Dim fileSavePath As String = Server.MapPath("uploads")
            If Not Directory.Exists(fileSavePath) Then
                Directory.CreateDirectory(fileSavePath)
            End If

            'after checking or creating folder it's time to save the file'
            fileSavePath = fileSavePath & "//" & fileName
            fuFileUploader.PostedFile.SaveAs(fileSavePath)
            Dim fileInfo As New FileInfo(fileSavePath)
            Using sqlConn As New SqlConnection(strConn)
                Using sqlCmd As New SqlCommand()
                    sqlCmd.CommandText = "INSERT INTO FileDetails" & ControlChars.CrLf &
                            "(FileName,FileSize,FileExtension,FilePath) " & ControlChars.CrLf &
                            "VALUES (@FileName,@FileSize,@FileExtension,@FilePath);"
                    sqlCmd.Parameters.AddWithValue("@FileName", fileName)
                    sqlCmd.Parameters.AddWithValue("@FileSize", fileInfo.Length.ToString())
                    sqlCmd.Parameters.AddWithValue("@FileExtension", fileExtension)
                    sqlCmd.Parameters.AddWithValue("@FilePath", fileSavePath)
                    sqlCmd.Connection = sqlConn
                    sqlConn.Open()
                    sqlCmd.ExecuteNonQuery()
                    sqlConn.Close()
                    BindGridviewFileData()
                End Using
            End Using

            lblMsg.Text = "File Uploaded Successfully!"
            lblMsg.ForeColor = System.Drawing.Color.Green
        Else
            lblMsg.Text = "Error: Please select a file to upload!"
        End If
    Catch
        lblMsg.Text = "Error: Error while uploading file!"
    End Try
End Sub

'download button to download files from gridview'
Protected Sub lnkDownloadMe_Click(ByVal sender As Object, ByVal e As EventArgs)
    Try
        Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
        Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
        Dim fileId As Integer = Convert.ToInt32(gvUploadedFiles.DataKeys(gvrow.RowIndex).Value.ToString())
        Using sqlConn As New SqlConnection(strConn)
            Using sqlCmd As New SqlCommand()
                sqlCmd.CommandText = "SELECT * FROM FileDetails WHERE FileId=@FileId"
                sqlCmd.Parameters.AddWithValue("@FileId", fileId)
                sqlCmd.Connection = sqlConn
                sqlConn.Open()
                Dim dr As SqlDataReader = sqlCmd.ExecuteReader()
                If dr.Read() Then
                    Dim fileName As String = dr("FileName").ToString()
                    Dim fileLength As String = dr("FileSize").ToString()
                    Dim filePath As String = dr("FilePath").ToString()
                    If File.Exists(filePath) Then
                        Response.Clear()
                        Response.BufferOutput = False
                        Response.ContentType = "application/octet-stream"
                        Response.AddHeader("Content-Length", fileLength)
                        Response.AddHeader("content-disposition", "attachment; filename=" & fileName)
                        Response.TransmitFile(filePath)
                        Response.Flush()
                    Else
                        lblMsg.Text = "Error: File not found!"
                    End If
                End If
            End Using
        End Using
    Catch
        lblMsg.Text = "Error: Error while downloading file!"
    End Try
End Sub

'bind file details to gridview'
Private Sub BindGridviewFileData()
    Try
        Using sqlConn As New SqlConnection(strConn)
            Using sqlCmd As New SqlCommand()
                sqlCmd.CommandText = "SELECT * FROM FileDetails"
                sqlCmd.Connection = sqlConn
                sqlConn.Open()
                gvUploadedFiles.DataSource = sqlCmd.ExecuteReader()
                gvUploadedFiles.DataBind()
                sqlConn.Close()
            End Using
        End Using
    Catch
    End Try
End Sub

Example Result

How to upload files to server folder for download in asp.net c# vb.net?
How to upload files to server folder for download in asp.net c# vb.net?

Download Example

 
That’s it, this way you can upload file to server folder to download in asp.net using c# or vb.net.

Let me know if you’ve any questions or doubts about this tutorial by writing down your queries in comment below. I would be happy to provide you my feedback as soon as possible.

Happy coding!

Previous articleHow to Validate Checkboxlist in jQuery [Quick Solutions]
Next articleValidate File Extension During File Upload using JavaScript in Asp.net
Hi there, I am Mayank, the man behind Technical Mack. I started AspnetO with a motive to educate people on various programming languages ranging from beginners to expert level. Through this blog, I aim to provide more insightful content.