download link for asp not working - c#

I am using the download link for my upload and download method in my ASP.NET Project. i created a database with fields
tFileName (nvarchar 100) , tFileupload (nvarchar 100), tFileData (varbinary (max)).
The data saves when I upload it and the fields are being saved. My problem is I can't seem to download the data from the database.
ill be posting my code and my c# codes. hope someone can help me. thanks!
My asp.net code, this code is inside my UpdatePanel also.
<asp:GridView ID="gvFile" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000" CellPadding="5">
<Columns>
<asp:BoundField DataField="tFileName" HeaderText="File Name" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click" CommandArgument='<%# Eval("TravelNumber") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is my code for my aspx.cs
public void getFile()
{
Utility u = new Utility();
string conn = u.local();
using (SqlConnection connUser = new SqlConnection(conn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select TravelNumber, tFileName from TravelTransaction";
cmd.Connection = connUser;
connUser.Open();
gvFile.DataSource = cmd.ExecuteReader();
gvFile.DataBind();
connUser.Close();
}
}
}
protected void lnkDownload_Click(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
Utility u = new Utility();
string conn = u.local();
using (SqlConnection connUser = new SqlConnection(conn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select tFileName, tFileUpload, tFileData from TravelTransaction where TravelNumber = #Trav";
cmd.Parameters.Add(new SqlParameter("#Trav", id));
cmd.Connection = connUser;
connUser.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["tFileData"];
contentType = sdr["tFileUpload"].ToString();
fileName = sdr["tFileName"].ToString();
}
connUser.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("content-disposition", "attachment;filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
I can't seem to find my error, actually there is no errors in it. But the file does not download and no action are happening. What is wrong with my code?

Related

Fill Data Table with image data as byte array in C#

So I have the data table filled but the column I need image data in is not working. I can see the table filled and can see it is reading the data, but not as a byte array, nor is it displaying the image.
public void Bindformview()
{
try
{
SqlDataAdapter adp = new SqlDataAdapter("Select * from Recipes", con);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
And I know I need to insert this code, or something like it that pulls the data out of the db "thumbnail varbinary(MAX)" column as a byte stream, to get the byte array for the image to display properly:
DataColumn column = new DataColumn("MyImage"); //Create the column.
column.DataType = System.Type.GetType("System.Byte[]"); //Type byte[] to store image bytes.
column.AllowDBNull = true;
column.Caption = "My Image";
table.Columns.Add(column); //Add the column to the table.
and this:
DataRow row = table.NewRow();
row["MyImage"] = <Image byte array>;
tables.Rows.Add(row);
But I do not need a new column or a new row as those fields are already there.
So how to I fill column "Thumbnail" in the data table, with byte array data to display and where do I do the insert of said code, before the if statement that loads the dt, in the if statement that binds the dt?
do I do it by stating the column like so:
dt.column.thumbnail.fill(byte[] bytes = (byte[])cmd.ExecuteScalar());
and then put this in to fill the formview image1 ID like so?
string strBase64 = Convert.ToBase64String(bytes);
formviewrecipes.Image1.ImageUrl = "data:Image/png;base64," + strBase64;
I am just at a standstill and not sure how to do this.
So to be clear, I already have the DB with the Proper image info, and can display it by <asp:image id=image1...etc />, with other code that retrieves the image outside of the formview using this code,
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetImageByID", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#Id",
Value = Request.QueryString["Id"]
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
}
but it doesn't work in a <asp:FormView...etc/> and I need to be able to have it do so for page formating.
This is why I was going in this direction, of using a Data Table right now. If you have a better solution I am open to trying it, as long as it can be used inside of the <asp:formview /> element. Thank you.
So I figured it out:
I Needed to add an Object o; and this line after the databind o = dt.Rows[0]["RecipeId"];
Like So:
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
//lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
o = dt.Rows[0]["RecipeId"];
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
and made the call to load the image as so:
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#RecipeId",
Value = o //Object from the datatable
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
if (bytes != null)
{
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
else
{
Image1.ImageUrl = "~/images/NoImageAvail.jpg";
}
}
Here is the code below if anyone else needs to do the same thing. I will be putting together a for/while or for/next for going through multiple data base entries to display at the same time instead of one at a time currently in this <asp:forview...></formview> element setup.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.IO;
using System.Data.SqlClient;
namespace DB_Test1
{
public partial class Search_Results_1 : System.Web.UI.Page
{
string b;
Object o;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Search"] != null)
{
if (Request.QueryString["Text"] != null)
{
string a = Request.QueryString["Text"];
b = a;
recipeSearch(a);
}
}
}
protected void recipeSearch(string a)
{
//Search the database
con.Open();
try
{
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM Recipes WHERE Type LIKE '%" + a + "%'", con);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
//lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
o = dt.Rows[0]["RecipeId"];
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
catch (Exception ex)
{
//throw new ApplicationException("operation failed!", ex);
}
con.Close();
FormViewRecipes.Visible = true;
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#RecipeId",
Value = o //Object from the datatable
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
if (bytes != null)
{
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
else
{
Image1.ImageUrl = "~/images/NoImageAvail.jpg";
}
}
Image1.Visible = true;
}
protected void FormViewRecipes_PageIndexChanging(object sender, FormViewPageEventArgs e)
{
string a = b;
FormViewRecipes.PageIndex = e.NewPageIndex;
recipeSearch(a);
}
}
}
And here is the ASPX page code:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<hr />
<div class="row">
<div class="col-md-8">
<table>
<tr>
<td>
<asp:Image ID="Image1" runat="server" visable="false" Height="150px" Width="150px"/>
</td>
<td>
<asp:FormView ID="FormViewRecipes" runat="server" DataKeyNames="RecipeId" AllowPaging="True"
onpageindexchanging="FormViewRecipes_PageIndexChanging" Visible="false">
<%--<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />--%>
<ItemTemplate>
<table style="border:1px solid #c1c1c1;">
<tr style="background-color:white;font-weight:bold"><td><%--Recipe Detail--%></td><td>
<%--<asp:Image id="Image1" runat="server" ImageUrl='<%# Eval("Thumbnail") %>'
AlternateText='<%# Eval("ThumbnailAltTxt") %>'
Height="100px" Width="100px" />--%></td>
</tr>
<tr><td><b>Title:- </b></td><td>
<asp:Label ID="lblRecipeTitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label></td></tr>
<tr><td><b>Ingredients:- </b></td><td>
<asp:Label ID="lblIngredients" runat="server" Text='<%# Eval("Ingredients") %>'></asp:Label></td></tr>
<tr><td><b>Directions:- </b></td><td>
<asp:Label ID="lblDirections" runat="server" Text='<%# Eval("Directions") %>'></asp:Label></td></tr>
<tr><td><b>Notes:- </b></td><td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Notes") %>'></asp:Label></td></tr>
</table>
</ItemTemplate>
<EmptyDataTemplate>
<table style="border:1px solid #c1c1c1;">
<tr style="background-color:#E5E5FE;font-weight:bold"><td><b>Recipe</b></td></tr>
<tr><td><b>Recipe Title:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
<tr><td><b>Recipe Ingredients:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
<tr><td><b>Recipe Directions:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
</table>
</EmptyDataTemplate>
</asp:FormView>
</td>
</tr>
</table>
</div>
<div class="col-md-4">
<p>Ad Space</p>
<asp:Label ID="lblDataTable" runat="server"></asp:Label>
</div>
</div>
</asp:Content>
Just remember I commented out the <asp:image..../a> element field that is in the <Asp:formview.../> element and reset my page layout to get how I wanted it to look for testing.

Can a data that show file path downloadable using c#

I am trying to make a page where the page can display a list of data and users can download the data. First, the data is a file name and the file name is like a filepath. For example C/user/file.pdf. Below is my coding:
protected void DownloadFile(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
//byte[] bytes;
string fileName;
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Ulysses"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT TOP 10 OLE_LINK_FILE_NAME FROM OLE_LINK";
//cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
fileName = sdr["OLE_LINK_FILE_NAME"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
//Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
Below is my HTML coding:
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="OLE_LINK_FILE_NAME" HeaderText="File Name"/>
<asp:TemplateField ItemStyle-HorizontalAlign = "Center">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
CommandArgument='<%# Eval("OLE_LINK_FILE_NAME") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Is it possible to download a data like that or not. If can, the page can display the data but I cannot download the file when I click the download link. Is there anything wrong with my coding? Here is the link of tutorial that I use as a guide: http://www.aspsnippets.com/Articles/Upload-and-Download-files-from-SQL-Server-Database-in-ASPNet.aspx

View pdf file in another page

Here have code to view pdf file and currently the file can be viewed in the same page.I want to display file in new page when the linkbutton clicked in gridview. As understood that Literal embed link needs to be changed but I am not sure about that. My question is how to view the file in new page?
Gridview code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="comName" HeaderText="Company Name" SortExpression="comName" />
<asp:BoundField DataField="sName" HeaderText="Stock Name" SortExpression="sName" />
<asp:BoundField DataField="annDate" HeaderText="Date Announced" SortExpression="annDate" />
<asp:BoundField DataField="fYearEnd" HeaderText="Financial Year End" SortExpression="fYearEnd" />
<asp:BoundField DataField="quarterr" HeaderText="Quarter" SortExpression="quarterr" />
<asp:BoundField DataField="QFREDate" HeaderText="Financial Period Ended " SortExpression="QFREDate" />
<asp:BoundField DataField="figure" HeaderText="Figure" SortExpression="figure" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" Text="View" OnClick="View" CommandArgument='<%# Eval("id") %>'></asp:LinkButton>
</ItemTemplate>
code behind for view:
protected void View(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
string embed = "<object data=\"{0}{1}\" type=\"application/pdf\" width=\"100%\" height=\"100%\">";
embed += "If you are unable to view file, you can download from here";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
ltEmbed.Text = string.Format(embed, ResolveUrl("~/FileCS.ashx?Id="), id);
}
FileCS.ashx code:
public void ProcessRequest(HttpContext context)
{
int id = int.Parse(context.Request.QueryString["Id"]);
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT fName, contentType, data FROM announ WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["data"];
contentType = sdr["contentType"].ToString();
fileName = sdr["fName"].ToString();
}
con.Close();
}
}
context.Response.Buffer = true;
context.Response.Charset = "";
if (context.Request.QueryString["download"] == "1")
{
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
}
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "application/pdf";
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
in your link button add OnClientClick="aspnetForm.target ='_blank';"
<asp:LinkButton ID="lnkView" runat="server" Text="View" OnClick="View" OnClientClick="aspnetForm.target ='_blank';" CommandArgument='<%# Eval("id") %>'></asp:LinkButton>
this will open a new tab.

C# grid view files doesnt open

I am uploading a file to my server and storing its file name and file path in the SQL database.
I am trying to display the file in the gridview... but doesn't open.
Below is my code
<asp:GridView ID="GridView1" runat="server" Width="45%" style="text-align:center;"
AutoGenerateColumns="false" HeaderStyle-ForeColor="White" DataKeyNames="TASK_ID"
AllowPaging ="true" emptydatatext="No Attachments" BackColor="AliceBlue" Font-Size = "11pt" AlternatingRowStyle-BackColor = "#F2F2F2" RowStyle-BorderWidth="1" AlternatingRowStyle-BorderWidth="1"
HeaderStyle-BackColor = "#00829c" HeaderStyle-BorderColor="#CC9966" HeaderStyle-BorderWidth="1px" HeaderStyle-BorderStyle="Solid">
<Columns>
<asp:BoundField DataField="TASK_ID" Visible="false" HeaderText="Id" />
<asp:BoundField DataField="ATTACH_FILENAME" HeaderText="FileName" />
<asp:TemplateField HeaderText="View" HeaderStyle-Width="90%">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" Target="_blank" runat="server" Text='<%# Eval("ATTACH_FILENAME") %>'
NavigateUrl='<%# Eval("ATTACH_FILEPATH") %>'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
private void Binddata()
{
string strQuery = "SELECT TASK_ID,ATTACH_FILENAME,ATTACH_FILEPATH from child_taskcreator where TASK_ID ='" + lblTaskid.Text + "'";
SqlCommand cmd = new SqlCommand(strQuery);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = connection;
connection.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
connection.Close();
return dt;
}
Please someone correct me... I wanted the users to open or save the document
// code to upload files
HttpFileCollection fileCollection = Request.Files;
if (fileCollection.Count != 0)
{
string filename = string.Empty;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile file = fileCollection[i];
filename = Path.GetFileName(file.FileName);
if (file.ContentLength > 0)
{
string strFilePath = "~/Uploads/";
System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(MapPath(strFilePath));
if (!DI.Exists)
{
System.IO.Directory.CreateDirectory(MapPath(strFilePath));
}
strFilePath = strFilePath + filename;
System.IO.FileInfo FI = new System.IO.FileInfo(MapPath(strFilePath));
if (!FI.Exists)
{
file.SaveAs(Server.MapPath(strFilePath));
}
// save the filepath variable to your database
}
}
}
Save the filepath variable to your database, then it will get retrieved from your gridview

Display data by claim numbers on grid view page

I am using C#. net and SQL server 2005.
I am uploading files (Word, PDF) into the database, and displaying on page using grid view.
I have different claim numbers, like co50000006 (like 10 rows). I mean the claim number has different files. I have other claim numbers on my table. (like c08000131, c01000001).
I want to display only one claim number rows on grid. I mean what ever number my querystring show I want to display the particular claim number on my grid.(Request.QueryString["ClaimNum"];).
Please help me with this.
I am getting claimnumber on table on my page header and I am inserting this value into the table.
protected void Page_Load(object sender, EventArgs e)
{
//Showing Claim Number on file upload.
lblFileUploadCliamNumber.Text = Request.QueryString["ClaimNum"];
}
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1" AllowPaging="True">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"
InsertVisible="False" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="ClaimNumber" HeaderText="Claim Number"
SortExpression="ClaimNumber" />
<asp:TemplateField HeaderText="Load Date">
<ItemTemplate>
<asp:Label runat="server" ID="LoadDate"
Text='<%# String.Format("{0:M/d/yyyy}", Eval("LoadDate")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="ContentType" HeaderText="ContentType"
SortExpression="ContentType" />
<asp:TemplateField HeaderText="Data">
<ItemTemplate>
<%--<asp:Image ID="Image1" runat="server"
ImageUrl='<%# "FileUploadHandler.ashx?ID=" + Eval("ID")%>'/>--%>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick = "Retreive_Doc">Download</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am using a SQL query here:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ AppSettings:connString %>"
SelectCommand="SELECT [ID], [ClaimNumber], [LoadDate], [Description], [ContentType], [Data]
FROM [tblFiles]"></asp:SqlDataSource>
Below are the my total code using in file upload.aspx.cs.
public partial class FileUpload : System.Web.UI.Page
{
private string redirectFrom = "FileUpload";
protected void Page_Load(object sender, EventArgs e)
{
//Showing Claim Number on file upload.
lblFileUploadCliamNumber.Text = Request.QueryString["ClaimNum"];
}
protected void Page_Init(object sender, EventArgs e)
{
WireEvents();
}
private void WireEvents()
{
btnFileUploadClose.Click += new EventHandler(btnFileUploadClose_Click);
}
private void btnFileUploadClose_Click(object sender, EventArgs e)
{
ReturnToClaimInfo();
}
private void ReturnToClaimInfo()
{
Response.Redirect(String.Format("/ClaimInfoView.aspx?ClaimNum={0}&ClaimCertSeqNo={1}&ClaimCovNum={2}&RedirectedFrom={3}"
, Request.QueryString["ClaimNum"]
, Request.QueryString["ClaimCertSeqNo"]
, Request.QueryString["ClaimCovNum"]
, redirectFrom));
}
/// Different file types start
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string strClaimNumber = lblFileUploadCliamNumber.Text.ToUpper();
string strDate = DateTime.Now.ToShortDateString();
string strDescription = txtDescription.Text.ToString();
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data, Description, ClaimNumber, LoadDate)" +
" values (#Name, #ContentType, #Data, #Description, #ClaimNumber, #LoadDate)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value
= contenttype;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add("#Description", SqlDbType.VarChar).Value = strDescription.ToString();
cmd.Parameters.Add("#ClaimNumber", SqlDbType.NVarChar).Value = strClaimNumber.ToUpper();
cmd.Parameters.Add("#LoadDate", SqlDbType.DateTime).Value = strDate.ToString();
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
if (lblMessage.Text == "File Uploaded Successfully")
{
txtDescription.Text = string.Empty;
}
//if(FileUpload1 != null)
//{
// lblMessage.Text = string.Empty;
//}
GridView1.DataBind();
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Word/PDF/Excel formats";
}
}
private Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.AppSettings["connString"];
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
//Retrieve doc
protected void Retreive_Doc(object sender, EventArgs e)
{
string strQuery = "select Name, ContentType, Data from tblFiles where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ((LinkButton) sender).CommandArgument;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
// Get data
public DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager
.AppSettings["connString"];
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
// download file
public void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
//end
}
}
Have you considered
SelectCommand="SELECT [ID], [ClaimNumber], [LoadDate], [Description], [ContentType], [Data] FROM [tblFiles] where [ClaimNumber] = " Request.QueryString["ClaimNum"]>

Categories