Monday, January 28, 2013

Upload and download files asp.net

Save/Upload files in folder and download files from folder in asp.net

Introduction: 
In this article I will explain how to save/upload files in folder and download files from folder system when click on link in gridview using asp.net.

Description: 

In many websites we will see download link whenever we click on that we will have a chance to download that files into our system. 

Generally we have different ways to save files like directly in our database or our project 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.
To implement this first design table in your database like below to save file details in database.
Column Name
Data Type
Allow Nulls
Id
int(set identity property=true)
No
FileName
varchar(50)
Yes
FilePath
varchar(50)
Yes

Now create new website after that right click on your website and add new folder and give name as Filesbecause 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
After that design your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Save and Download Files from file system</title>
<style type="text/css">
.modalBackground
{
background-colorGray;
filteralpha(opacity=80);
opacity0.8;
z-index10000;
}

.GridviewDiv {font-size100%font-family'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial,Helevetica, sans-serifcolor#303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em0.5em;}
.Gridview tr{colorBlackbackground-colorWhitetext-align:left}
:link,:visited { color#DF4F13text-decoration:none }

</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileUpload1" runat="server" /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
</div>
<div>
<asp:GridView ID="gvDetails" CssClass="Gridview" runat="server" AutoGenerateColumns="false"DataKeyNames="FilePath">
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
After completion of aspx page design add the following namespaces in code behind

C# Code


using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;
After that write the following code in code behind


private SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridviewData();
}
}
// Bind Gridview Data
private void BindGridviewData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from FilesTable",con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
// Save files to Folder and files path in database
protected void btnUpload_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
fileUpload1.SaveAs(Server.MapPath("Files/"+filename));
con.Open();
SqlCommand cmd = new SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)",con);
cmd.Parameters.AddWithValue("@Name",filename );
cmd.Parameters.AddWithValue("@Path""Files/"+filename );
cmd.ExecuteNonQuery();
con.Close();
BindGridviewData();
}
// This button click event is used to download files from gridview
protected void lnkDownload_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
string filePath = gvDetails.DataKeys[gvrow.RowIndex].Value.ToString();
Response.ContentType = "image/jpg";
Response.AddHeader("Content-Disposition""attachment;filename=\"" + filePath + "\"");
Response.TransmitFile(Server.MapPath(filePath));
Response.End();
}
VB.NET Code

Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.UI.WebControls

Partial Class Default
Inherits System.Web.UI.Page
Private con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridviewData()
End If
End Sub

' Bind Gridview Data
Private Sub BindGridviewData()
con.Open()
Dim cmd As New SqlCommand("select * from FilesTable", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
con.Close()
gvDetails.DataSource = ds
gvDetails.DataBind()
End Sub

' Save files to Folder and files path in database
Protected Sub btnUpload_Click(ByVal sender As ObjectByVal e As EventArgs)
Dim filename As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
fileUpload1.SaveAs(Server.MapPath("Files/" & filename))
con.Open()
Dim cmd As New SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)", con)
cmd.Parameters.AddWithValue("@Name", filename)
cmd.Parameters.AddWithValue("@Path""Files/" & filename)
cmd.ExecuteNonQuery()
con.Close()
BindGridviewData()
End Sub

' This button click event is used to download files from gridview
Protected Sub lnkDownload_Click(ByVal sender As ObjectByVal e As EventArgs)
Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Dim filePath As String = gvDetails.DataKeys(gvrow.RowIndex).Value.ToString()
Response.ContentType = "image/jpg"
Response.AddHeader("Content-Disposition""attachment;filename=""" & filePath & """")
Response.TransmitFile(Server.MapPath(filePath))
Response.[End]()
End Sub
End Class



Demo




You might also Like:






Send Email using ASP.NET C#

How to send email using asp.net
In this article I will explain how to send email using asp.net.

Description:

In realtime we will use gmail,yahoo,hotmail etc to send mails to particular user here I will show to how to implement mail sending concept in asp.net.

To implement mail concept in asp.net first we need to add following reference to our applicationSystem.Web.Mail namespace 

What is System.Web.Mail

System.Web.Mail is a namespace which contains classes that enable us to construct and send messages using the CDOSYS (Collaboration Data Objects for Windows 2000) message component. The mail message is delivered either through the SMTP mail service built into Microsoft Windows 2000 or through an arbitrary SMTP server.

How we can get this reference (System.Web.Mail

We need to add System.web.dll reference to our application for that follow below steps

a                 a)  On the Project menu, click Add Reference.
b)    On the .NET tab, locate System.Web.dll, and then click Select.
c)     Click OK in the Add References.

After that design your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Send Mail using asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style=" border:1px solid" align="center">
<tr>
<td colspan="2" align="center">
<b>Send Mail using asp.net</b>
</td>
</tr>
<tr>
<td>
From:
</td>
<td>
<asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Subject:
</td>
<td>
<asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
To:
</td>
<td>
<asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td valign="top">
Body:
</td>
<td>
<asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Columns="30" Rows="10" ></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" Text="Send" runat="server" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Now add following namcespaces in your codebehind



using System.Web.Mail;
After that write the following code in button click



protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
MailMessage Msg = new MailMessage();
// Sender e-mail address.
Msg.From = txtFrom.Text;
// Recipient e-mail address.
Msg.To = txtTo.Text;
Msg.Subject = txtSubject.Text;
Msg.Body = txtBody.Text;
// your remote SMTP server IP.
SmtpMail.SmtpServer = "10.20.72.1";
SmtpMail.Send(Msg);
Msg = null;
Page.RegisterStartupScript("UserMsg""<script>alert('Mail sent thank you...');if(alert){ window.location='SendMail.aspx';}</script>");
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
Here use your SMTP server address then only it will work for you and check mails in spam also because sometimes mails should be appear in spam folder also.



Demo