Friday, 28 March 2014

How to upload or Save files in folder and download files when click on Download link in gridview using asp.net

In this article I will explain how to upload or Save files in folder and download files when click on Download link in gridview using asp.net.

We have different ways to save files in our project Solution explorer under folder. If we save files in our database it will occupy more space so it will create problem for us after host website because host providers will provide limited space for us we can solve this problem by saving files in our project folder.

Below is the DataBase design screen (Table Design). 


 First we need to create a new website. After that right click on your website and add new folder and give name as Files because here I am using same name for my sample if you want to change folder name you need to change the Files folder name in your code behind also

We need to establish a Database connection in web.config file

<connectionStrings>
<add name="connectionString" connectionString="Data Source=LocalHost;uid=sa1;password=Con@123;Initial Catalog=practice"/>
</connectionStrings>


After that you need to design aspx page. Below is the sample code for Page design.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.gvColours {
font-family: Arial;
font-size: 10pt;
font-weight: normal;
color: white;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
File Name :
<asp:TextBox runat="server" ID="txtFileName"></asp:TextBox>
</div>
<br />
<br />
<div>
File Location :
<asp:FileUpload ID="fileUpload1" runat="server" /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
</div>
<br />
<br />
<div>
<asp:GridView runat="server" ID="gvFileDetails" AutoGenerateColumns="false" DataKeyNames="FileUrl"
CssClass="gvColours" Width="500px" HeaderStyle-BackColor="Maroon">
<Columns>
<asp:BoundField DataField="FileID" HeaderText="Id" ItemStyle-ForeColor="Black" />
<asp:BoundField DataField="FileName" HeaderText="FileName" ItemStyle-ForeColor="Black" />
<asp:TemplateField HeaderText="FilePath" >
<ItemTemplate>
<asp:LinkButton ID="lnkAttachment" runat="server" OnClick="lnkAttachment_Click" Text="Attachment" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

Below is the design screen.

After that we need to write code for to insert Files into our project solution under Files (folder name) and insert file path into database and display File names in GridView from Files folder based on Files path in database

Add below NameSpaces 

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

public partial class UpLoadFiles : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindFileInfoToGrid();
}
}
// Bind Data to Gridview use DataSet
private void BindFileInfoToGrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from FileDetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet dsFileInfo = new DataSet();
da.Fill(dsFileInfo);
con.Close();
gvFileDetails.DataSource = dsFileInfo;
gvFileDetails.DataBind();
}
// Save files to Solution Expolorer Folder and files path in database
protected void btnUpload_Click(object sender, EventArgs e)
{
string FileNameSave = txtFileName.Text;
string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
fileUpload1.SaveAs(Server.MapPath("Files/" + filename));
con.Open();
SqlCommand cmd = new SqlCommand("insert into FileDetails(FileName,FileUrl) values(@FileName,@FileUrl)", con);
cmd.Parameters.AddWithValue("@FileName", FileNameSave);
cmd.Parameters.AddWithValue("@FileUrl", "Files/" + filename);
cmd.ExecuteNonQuery();
con.Close();
//After saved information in database than bind data to gridview
BindFileInfoToGrid();
}
// This Link Button click event is used to download Attachment files from gridview
protected void lnkAttachment_Click(object sender, EventArgs e)
{
LinkButton lnkFindLinkButton = sender as LinkButton;
GridViewRow gvFindRow = lnkFindLinkButton.NamingContainer as GridViewRow;
string filePath = gvFileDetails.DataKeys[gvFindRow.RowIndex].Value.ToString();
Response.ContentType = "image/jpg";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
Response.TransmitFile(Server.MapPath(filePath));
Response.End();
}
}

Output:




No comments:

Post a Comment