Solved

Retrieve file from database

Posted on 2013-01-07
11
249 Views
Last Modified: 2013-01-09
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
Comment
Question by:asp_net2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 42

Expert Comment

by:sedgwick
ID: 38750848
do u create the control dynamically?
cause you can set the NavigateUrl property of the control to the file path.
0
 
LVL 19

Expert Comment

by:Manoj Patil
ID: 38750961
To bind the file to Hyperlink you can simply add like this

HyperLink1.NavigateUrl=String.IsNullOrEmpty(retrievedFile);
0
 
LVL 16

Expert Comment

by:Easwaran Paramasivam
ID: 38750979
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
Independent Software Vendors: 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!

 
LVL 19

Accepted Solution

by:
Manoj Patil earned 500 total points
ID: 38750992
If you are binding in aspx page :
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl= '<%# Bind("filename") %>' Text= '<%# Bind("filename") %>' ></asp:HyperLink>
0
 
LVL 4

Author Comment

by:asp_net2
ID: 38751041
@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
 
LVL 19

Expert Comment

by:Manoj Patil
ID: 38751067
0
 
LVL 4

Author Comment

by:asp_net2
ID: 38751074
@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
 
LVL 19

Expert Comment

by:Manoj Patil
ID: 38751098
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
 
LVL 4

Author Comment

by:asp_net2
ID: 38756536
@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
 
LVL 19

Expert Comment

by:Manoj Patil
ID: 38756730
That is what I have already posted in my previous comment !!
HyperLink1.NavigateUrl
0
 
LVL 4

Author Comment

by:asp_net2
ID: 38757256
Sorry, I must have missed that. My bad.
0

Featured Post

More Than Just A Video Library

Train for your certification. Learn the latest DevOps tools. Grow your skillset to do better work.

At Linux Academy, we release new training modules every week so you'll always be up to date on the latest tech.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question