• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 253
  • Last Modified:

Retrieve file from database

Hello Experts,

I have an application that stores .doc, .pdf, .xls, .png, and .jpg files in my database. This all works with no errors. I can also retrieve the files to a GridView control with no problems.

The problem that I need help with is how to retrieve the file to a HyperLink control by binding all the data to a DataTable. Please see my CodeBehind below. I simple need to retrieve the file to a control such as a HyperLink control and not sure how to do so.

CodeBehind:
protected void RetrieveTicketsToModifyByID()
    {
        int TicketID = Convert.ToInt32(Request.QueryString["tkt_id"].ToString());

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CMDB"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "RetrieveTicketsToModifyByID";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.AddWithValue("@tkt_id", SqlDbType.Int).Value = TicketID;

            DataTable dtTicketsToModify = new DataTable();

            SqlDataAdapter adp = new SqlDataAdapter();

            try
            {
                conn.Open();

                adp.SelectCommand = cmd;
                adp.Fill(dtTicketsToModify);

                if ((dtTicketsToModify != null))
                {
                    DataRow data = dtTicketsToModify.Rows[0];

                    lblCreationDateValue.Text = Convert.ToDateTime(data["tkt_cre_dt"]).ToShortDateString();
                    txtUserRequestChange.Text = data["tkt_usr_req_chg"].ToString();
                    ddlCompany.SelectedValue = data["com_id"].ToString();
                    ddlRequestType.SelectedValue = data["req_typ_id"].ToString();
                    ddlStatusType.SelectedValue = data["sts_id"].ToString();
                    ddlTicketOwner.SelectedValue = data["ownr_id"].ToString();
                    txtShortDesc.Text = data["tkt_short_desc"].ToString();
                    txtTicketDesc.Text = data["tkt_desc"].ToString();
                    txtTicketResolution.Text = data["tkt_resolution"].ToString();

                    //txtCompletionDate.Text = string.Empty;
                    //if (data["tkt_cmpl_dt"] != DBNull.Value && !string.IsNullOrEmpty(Convert.ToString(data["tkt_cmpl_dt"])))
                    //    txtCompletionDate.Text = Convert.ToDateTime(data["tkt_cmpl_dt"]).ToShortDateString();

                    string tkt_filename = null;
                    if (data["tkt_filename"] != DBNull.Value)
                    {
                        tkt_filename = data["tkt_filename"].ToString();
                    }

                    if (!string.IsNullOrEmpty(tkt_filename))
                    {
                        lblVerificationFormFileName.Visible = true;
                        lblVerificationFormFileName.Text = "You have a file named " + "'" + tkt_filename + "'" + " in our system.";
                    }
                }
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }
    }

Open in new window


Thanks in advance!
0
asp_net2
Asked:
asp_net2
1 Solution
 
Meir RivkinFull stack Software EngineerCommented:
do u create the control dynamically?
cause you can set the NavigateUrl property of the control to the file path.
0
 
Manoj PatilSr. Software EngineerCommented:
To bind the file to Hyperlink you can simply add like this

HyperLink1.NavigateUrl=String.IsNullOrEmpty(retrievedFile);
0
 
Easwaran ParamasivamCommented:
I hope in the grid you would have Unique ID column. If not, have it.

Create a hyper link column and pass the ID as an argument to launch another page. In the page, parse the query string and get the content of the file from database for that ID.

Write the content in the webpage (Create an empty ASPX page for it)



To launch new page in hyperlink:

http://datawebcontrols.com/faqs/Hyperlinks/HyperlinkThatOpensInANewWindow.shtml
http://yasserzaid.wordpress.com/2008/12/20/open-popup-window-with-hyperlink-inside-gridview/
http://nice-tutorials.blogspot.in/2009/03/opening-pop-up-window-from-datagrid.html

To show file content in a webpage:

http://www.codeproject.com/Articles/15649/Create-and-download-text-file-from-a-web-page

HTH
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Manoj PatilSr. Software EngineerCommented:
If you are binding in aspx page :
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl= '<%# Bind("filename") %>' Text= '<%# Bind("filename") %>' ></asp:HyperLink>
0
 
asp_net2Author Commented:
@techChallenger1,

I tried adding HyperLink1.NavigateUrl=String.IsNullOrEmpty(retrievedFile); but I'm getting red lines.

Also, i'm not binding to GridView. I'm trying to bind the file to a HyperLink control on my page. In order for this to work when binding to the GridView control I had to point to another page that processed the code based on the ID of the record that I need the image for. That page was called retrieve_file.aspx. Please see the codebehind for that below.

This time I need to retrieve the file to the HyperLink control to a page and NOT a GridView control. So i'm not sure if I still need the HyperLink control to point to the same page or not.

Retrieve File CodeBehind:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Security.Cryptography;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Security.Cryptography;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Text;

public partial class tickets_retrieve_file : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        RetrieveTicketsFile();
    }

    protected void RetrieveTicketsFile()
    {
        int tkt_id = Convert.ToInt32(Request.QueryString["tkt_id"]);

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CMDB"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "RetrieveTicketsFile";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.AddWithValue("@tkt_id", SqlDbType.Int).Value = tkt_id;

            byte[] arrContent = null;

            conn.Open();

            SqlDataReader rdr = cmd.ExecuteReader();

            if (rdr.Read())
            {
                //Get the buffer size, Assuming the file is in the column Zero
                long buffsize = rdr.GetBytes(0, 0, arrContent, 0, 0);
                arrContent = new byte[buffsize];

                //Get the data, Assuming the file is in the column Zero
                long bytesread = rdr.GetBytes(0, 0, arrContent, 0, (int)buffsize);
                // bytesread  should be equal buffsize

                //Assuming the mimetype is in the column One
                string conType = rdr.GetString(2);
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = conType;

                //You must set the filename.
                //string filename = "PricePackage.doc";
                string filename = rdr.GetString(1);
                //Response.AddHeader("content-disposition", "attachment;filename=" + filename);
                //Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".pdf");
                Response.AddHeader("content-disposition", "attachment;filename=" + filename);

                //And the size
                Response.AddHeader("Content-Length", buffsize.ToString());

                //Assuming "pp_size" is in the column Two
                //Response.Write(arrContent.ToString());
                Response.BinaryWrite(arrContent);
                Response.Flush();
                Response.End();
            }
        }
    } 
}

Open in new window

0
 
Manoj PatilSr. Software EngineerCommented:
0
 
asp_net2Author Commented:
@techChallenger1,

The link you sent me is retrieving the file to a GridView control. I need to retrieve the image to a HyperLink control that is NOT inside of any GridView control.
0
 
Manoj PatilSr. Software EngineerCommented:
What you can do is,
add an <a> tag in your aspx page
<a id="downloadFile" runat="server></a>
And when you retrieve the file from database, after the statement add following code.

string FileName=rdr.GetString(1);
downloadFile.Href="http://xyz.com/" + FileName +".extension";

This will also do the same function like download.
0
 
asp_net2Author Commented:
@techChallenger1,

Thank you for your help. I was able to figure out the issue on my own. Please see what I had to add to my CodeBehind and Markup:

CodeBehind:
string fileExists = data["tkt_size"].ToString();
                        if (fileExists == "0")
                        {
                            hlFile.Visible = false;
                        }

                        else
                        {
                            hlFile.NavigateUrl = String.Format("retrieve_file.aspx?tkt_id={0}", data["tkt_id"].ToString());
                        }


Markup:
<asp:HyperLink ID="hlFile" runat="server">Open/Save File</asp:HyperLink>
0
 
Manoj PatilSr. Software EngineerCommented:
That is what I have already posted in my previous comment !!
HyperLink1.NavigateUrl
0
 
asp_net2Author Commented:
Sorry, I must have missed that. My bad.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now