ASP.NET How to Upload and Download Files with SQL Database

  • by
asp.net-file-upload-and-download-with-sql-database

Hi Friends,
In this post we will see how we can upload and download files in asp.net. We will upload files and its name and store it in sql server database and retrieve back the data to display it on asp.net gridview. So let’s start.

ASP.NET Upload and Download Files:


DOWNLOAD SOURCE CODE

Create a webform with name WebForm2.aspx and edit it as below:

WebForm.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.NET Uploading and Downloading Files</title>
<link href="bootstrap.min.css" rel="stylesheet" />

<style>
.mytable {
width: 50%;
margin: 10px;
}

body {
padding: 5px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>ASP.NET - Uploading and Downloading files</h2>
<table class="table table-condensed mytable">
<tr>
<td>File Name:
</td>
<td>
<asp:TextBox runat="server" ID="txtFileName" Width="150" />
</td>
</tr>
<tr>
<td>Select File:
</td>
<td>
<asp:FileUpload runat="server" ID="fileupload1" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button runat="server" ID="btnUpload" OnClick="btnUpload_Click" Text="Submit" CssClass="btn btn-success" />
</td>
</tr>
</table>
<asp:Label runat="server" ID="lblInfo" />
<asp:GridView runat="server" ID="gridviewFiles" UseAccessibleHeader="true" CssClass="table table-hover table-condensed mytable" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Id" DataField="Id" />
<asp:BoundField HeaderText="File name" DataField="FileN" />

<asp:TemplateField HeaderText="File">
<ItemTemplate>
<asp:LinkButton runat="server" Text='<%# Eval("FilePath") %>'
OnClick="FileDownload_Clicked"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

This form contains an asp.net file upload control to upload files and a textbox to enter file name (like a description of uploaded files) and a gridview with download link to the stored file. The download link is shown using asp:linkbutton which will display the file name stored in the database. So when the user is uploading file we will first file in a folder and stored its name in sql database using which we can retrieve the file back.

asp.net-file-upload-and-download-with-sql-database

asp.net file upload and download with sql database preview

And edit the code as below:

WebForm2.aspx.cs:

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

namespace WebApplication1
{
public partial class WebForm2 : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adapter;
SqlCommand cmd;
static String connectionString = @"Data Source=192.168.100.45;Initial Catalog=ParallelCodes;User ID=sa;Password=789;Integrated Security=True;";

protected void Page_Load(object sender, EventArgs e)
{
FillGrid();
}

protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
String filePath = Server.MapPath("~/Files/" + fileupload1.FileName);

fileupload1.SaveAs(filePath);
lblInfo.Text = "Your file was successfully uploaded to : Files/"
+ Path.GetFileName(fileupload1.FileName).ToString();

con = new SqlConnection(connectionString);
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "sp_AddFiles";
cmd.Parameters.AddWithValue("@FileN", txtFileName.Text.ToString());
cmd.Parameters.AddWithValue("@FilePath", fileupload1.FileName);
cmd.ExecuteNonQuery();

cmd.Dispose();
con.Dispose();
con.Close();

lblInfo.Text = "Saved successfully.";

txtFileName.Text = "";

FillGrid();
}
catch (Exception ex)
{
lblInfo.Text = ex.Message.ToString();
}
}

public void FillGrid()
{
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand();
con.Open();
cmd = new SqlCommand("Select * from tblFiles", con);
adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);

gridviewFiles.DataSource = dt;
gridviewFiles.DataBind();

cmd.Dispose();
con.Dispose();
con.Close();

}
catch (Exception ex)
{

}
}

protected void FileDownload_Clicked(object sender, EventArgs e)
{
try
{
var element = (LinkButton)sender;

String filename = element.Text.ToString();
String filepath = Server.MapPath("Files/" + filename);

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.Flush();

Response.TransmitFile(filepath);
Response.End();
}
catch(Exception ex)
{

}
}
}
}

This is my database script which I used to stored all the data for uploading and downloading file.

dbscript.sql:

create table tblFiles
(
Id int primary key identity(1,1) not null,
FileN nvarchar(50),
FilePath nvarchar(max)
)

alter procedure sp_AddFiles
(
@FileN nvarchar(50),@FilePath nvarchar(max)
)
as begin
Insert into tblFiles (FileN,FilePath) values (@FileN,@FilePath)
end

--truncate table tblFiles
---Select * from tblFiles

DOWNLOAD SOURCE CODE

Also see:

Angular JS Bind Grid Html Table from SQL in ASP.NET MVC C#.

Creating AngularJS Login form in MVC ASP.NET Forms C#.

How to Upload File ASP.NET MVC with Database.

How to upload files in ASP.NET?

How to download files in ASP.NET?

ASP.NET Gridview CSS design using Bootstrap.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.