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
Related
I created a grid view that contains a column for images, after I write all necessary code the image is still not showing. Can you look at the code and see if there is something that i'm doing wrong? This is my ASP.NET Grid View:
<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="False" Height="229px" Width="404px">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<img id="img1" src='Handler1.ashx.cs?ProductID=<%# Eval("ProductID").ToString() %>' height="70" width="70"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" CommandArgument='<%# Eval("ProductID") %>' OnClick="lnk_OnClick">View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my button that when clicked should display the images in the ASP.NET grid view
protected void btnSave_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("ProductCreateOrUpdate", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#ProductID", (hfProductID.Value == "" ? 0 : Convert.ToInt32(hfProductID.Value)));
sqlCmd.Parameters.AddWithValue("#Name", txtName.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Image", FileUpload2.FileBytes);
sqlCmd.Parameters.AddWithValue("#Description", txtDescription.Text.Trim());
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
string productID = hfProductID.Value;
Clear();
if (productID == "")
lblSuccessMessage.Text = "Saved Successfully";
else
lblSuccessMessage.Text = "Updated Successfully";
FillGridView();
}
And this is the general Handler.ashx
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string Constr = System.Configuration.ConfigurationManager.ConnectionStrings[#"connection String"].ToString();
string pici = context.Request.QueryString["ProductID"];
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(Constr))
{
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT Image FROM Product WHERE ProductID=#ProductID", conn))
{
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("ProductID", pici));
conn.Open();
using (System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("Image")]);
reader.Close();
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
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?
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.
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
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"]>