Application which can download a file and upload file

Posted by Shitalr under ASP.NET on 9/6/2013 | Points: 10 | Views : 1869 | Status : [Member] | Replies : 5
hi,
how can i create a web page where user can download a file and can upload also!




Responses

Posted by: Bandi on: 9/6/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Refer this link:
http://www.codeproject.com/Articles/308552/Upload-and-Download-Files-to-SQL-Servers-in-ASP-Ne

Check the "ASP.NET File Download" & "ASP.NET File Upload" sections in the link http://msdn.microsoft.com/en-us/library/aa478985.aspx#aspnet-jspmig-downloadinganduploading_topic6

Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Shitalr, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Satyapriyanayak on: 9/6/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
http://www.aspdotnet-suresh.com/2012/02/saveupload-files-in-folder-and-download.html
http://www.codeproject.com/Articles/308552/Upload-and-Download-Files-to-SQL-Servers-in-ASP-Ne
http://www.codeproject.com/Tips/185886/File-Upload-and-Download-in-ASP-NET

If this post helps you mark it as answer
Thanks

Shitalr, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 9/6/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
--Table structure
CREATE TABLE FilesTable (Id int identity , FileName varchar(50) , FilePath varchar(50) )


--FileUpAndDownload.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpAndDownload.aspx.cs" Inherits="FileUploadAndDownload.FileUpAndDownload" %>


<!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 id="Head1" runat="server">
<title>Save and Download Files from file system</title>
<style type="text/css">
.modalBackground
{
background-color: Gray;
filter: alpha(opacity=80);
opacity: 0.8;
z-index: 10000;
}


.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;}
.Gridview tr{color: Black; background-color: White; text-align:left}
:link,:visited { color: #DF4F13; text-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>


--"FileUpAndDownload.aspx.cs"
using System;

using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FileUploadAndDownload
{
public partial class FileUpAndDownload : System.Web.UI.Page
{
private SqlConnection con = new SqlConnection("Data Source=XXXXX;Integrated Security=true;Initial Catalog=DBName");
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 [DotNet].[FilesTab]", 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)); // Create "Files" folder in the server path
con.Open();
SqlCommand cmd = new SqlCommand("insert into [DotNet].[FilesTab](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();
}
}
}


Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Shitalr, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Allemahesh on: 9/6/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
You can use the below code:-

DataTable:-

Column Name Data Type

Id int
FileName varchar(50)
FileType varchar(50)
FileData varchar(Max)


.aspx page.

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1">
<title>Upload Word Files to Database and Download files from database in asp.net
</title>
</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" runat="server" AutoGenerateColumns="false" DataKeyNames="Id">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<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>


C# Code

using System;

using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;
string strCon = "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()
{
using (SqlConnection con=new SqlConnection(strCon))
{
using (SqlCommand cmd=new SqlCommand())
{
cmd.CommandText = "select * from FileInformation";
cmd.Connection = con;
con.Open();
gvDetails.DataSource = cmd.ExecuteReader();
gvDetails.DataBind();
con.Close();
}
}
}
// Save files to Folder and files path in database
protected void btnUpload_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
Stream str = fileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(str);
Byte[] size = br.ReadBytes((int) str.Length);
using (SqlConnection con=new SqlConnection(strCon))
{
using (SqlCommand cmd=new SqlCommand())
{
cmd.CommandText = "insert into FileInformation(FileName,FileType,FileData) values(@Name,@Type,@Data)";
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@Type", "application/word");
cmd.Parameters.AddWithValue("@Data", size);
cmd.Connection =con;
con.Open();
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;
int fileid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value.ToString());
string name, type;
using (SqlConnection con=new SqlConnection(strCon))
{
using (SqlCommand cmd=new SqlCommand())
{
cmd.CommandText = "select FileName, FileType, FileData from FileInformation where Id=@Id";
cmd.Parameters.AddWithValue("@id", fileid);
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
Response.ContentType = dr["FileType"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" +dr["FileName"] + "\"");
Response.BinaryWrite((byte[])dr["FileData"]);
Response.End();
}
}
}
}



VB.NET Code

Imports System.Data.SqlClient

Imports System.IO
Imports System.Web.UI.WebControls
Partial Class VBCode
Inherits System.Web.UI.Page
Private strCon As String = "Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridviewData()
End If
End Sub
' Bind Gridview Data
Private Sub BindGridviewData()
Using con As New SqlConnection(strCon)
Using cmd As New SqlCommand()
cmd.CommandText = "select * from FileInformation"
cmd.Connection = con
con.Open()
gvDetails.DataSource = cmd.ExecuteReader()
gvDetails.DataBind()
con.Close()
End Using
End Using
End Sub
' Save files to Folder and files path in database
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim filename As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
Dim str As Stream = fileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(str)
Dim size As [Byte]() = br.ReadBytes(CInt(str.Length))
Using con As New SqlConnection(strCon)
Using cmd As New SqlCommand()
cmd.CommandText = "insert into FileInformation(FileName,FileType,FileData) values(@Name,@Type,@Data)"
cmd.Parameters.AddWithValue("@Name", filename)
cmd.Parameters.AddWithValue("@Type", "application/word")
cmd.Parameters.AddWithValue("@Data", size)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
BindGridviewData()
End Using
End Using
End Sub
' This button click event is used to download files from gridview
Protected Sub lnkDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Dim fileid As Integer = Convert.ToInt32(gvDetails.DataKeys(gvrow.RowIndex).Value.ToString())
Dim name As String, type As String
Using con As New SqlConnection(strCon)
Using cmd As New SqlCommand()
cmd.CommandText = "select FileName, FileType, FileData from FileInformation where Id=@Id"
cmd.Parameters.AddWithValue("@id", fileid)
cmd.Connection = con
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
If dr.Read() Then
Response.ContentType = dr("FileType").ToString()
Response.AddHeader("Content-Disposition", "attachment;filename=""" & Convert.ToString(dr("FileName")) & """")
Response.BinaryWrite(DirectCast(dr("FileData"), Byte()))
Response.[End]()
End If
End Using
End Using
End Sub
End Class


Links :
1. http://www.aspdotnet-suresh.com/2013/01/aspnet-download-and-upload-files-to.html
2. http://www.aspdotnet-suresh.com/2012/02/saveupload-files-in-folder-and-download.html


Shitalr, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 9/6/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
File Upload by using WebClient
System.Net.WebClient webClient = new System.Net.WebClient(); 

string sourceFilePath = @"D:\MyDocuments\DataFile.xml" ;
string webAddress = "http://www.YourDomainName.com/ClientFiles/";
string destinationFilePath= webAddress + "DataFile.xml";
webClient.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
webClient.UploadFile(destinationFilePath, "PUT", sourceFilePath);
webClient.Dispose();


References for UploadFile & DownlaodFile by using WebClient of System.Net namespace
http://geekswithblogs.net/pranav/archive/2009/10/26/uploading-and-downloading-files-to-a-website-using-c.aspx
http://chiragvidani.blogspot.in/2011/10/how-to-uploaddownload-file-tofrom.html
http://www.dotnetbull.com/2011/09/uploading-files-from-client-side-to-ftp.html

Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Shitalr, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response