0

I have a fileupload control that uploads an image to a SQL Server 2008 database and I want to download it with a save dialog pop up box. The code to download the file executes fine but nothing happens when I click on the download linkbutton. The event fires from the code behind. My only guess is that it is the modal popup again that is causing the issue.

<Modalpopup>
</ModalPopup>
<UpdatePanel>
   --DetailsView
    --------LinkButton(Download)
   --DetailsView
</UpdatePanel>

Is the structure of the page.

<!-- Details View here -->
            <asp:DetailsView ID="dvReviewCases" runat="server" Height="50px" 
                AutoGenerateRows="False" CssClass="dvCSS" 
                OnDataBound="dvADReviewCases_DataBound" 
                onpageindexchanging="dvReviewCases_PageIndexChanging" onitemcommand="dvReviewCases_ItemCommand"
                 >
                <Fields>

                    <asp:TemplateField HeaderStyle-CssClass="dvHeaderStyle" HeaderText="Evidence" ItemStyle-CssClass="dvValueField" > 
                        <ItemTemplate>
                            <asp:LinkButton ID="btnDownload" runat="server" Text='<%#Eval("evidenceID") %>' CommandName="Download" >
                            </asp:LinkButton>
                        </ItemTemplate>    
                    </asp:TemplateField>


                </Fields>
            </asp:DetailsView>

Code Behind

    // Download file from Evidence table
    protected void dvReviewCases_ItemCommand(object sender, DetailsViewCommandEventArgs e)
    {
        if (e.CommandName == "Download")
        {
            String strCaseID = Session["caseID"].ToString();
            String strEvidenceID = Session["evidenceID"].ToString();

            //Search for evidence file
            DbCommand cmd = GetData.CreateCommand("ADGetEvidence");
            GetData.AddParameter(cmd, strEvidenceID, "@evidenceID");
            GetData.AddParameter(cmd, strCaseID, "@caseID");
            GetData.GetResults(cmd);

            // Check if datatable has row returned
            if (GetData.getTable().Rows.Count > 0)
            {
                String fileName = "Evidence" + Session["caseID"].ToString();
                byte[] file = null;
                String fileType = GetData.getTable().Rows[0][1].ToString();

                // Typecast resulting row to byte
                file = ((byte[])GetData.getTable().Rows[0][0]);
                Response.ContentType = fileType;

                // Give user option to download file
                Response.AddHeader("Content-Disposition","attachment;filename=" + fileName);
                Response.BinaryWrite(file);

                Response.End();

            }

        }
    }
1
  • I've tried adding the btnDownload as a trigger for the update panel but it gave me an error that it cannot find the button when I ran the page. Commented Nov 26, 2012 at 20:44

2 Answers 2

1

Why dont you try by using query string . Here is my code where in query string is used and i fetch images from the database without having to create the any instatnce of that desired image inyour local folder. Hop this helps.

<%@ WebHandler Language="C#" Class="DisplayImg" %>

using System;
using System.Web;
using System.Configuration;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class DisplayImg : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string theID;
        if (context.Request.QueryString["id"] != null)
            theID = context.Request.QueryString["id"].ToString();
        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/jpeg";
        Stream strm = DisplayImage(theID);
        byte[] buffer = new byte[2048];
        int byteSeq = strm.Read(buffer, 0, 2048);

        while (byteSeq > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 2048);
        }
    }

    public Stream DisplayImage(string theID)
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SERVER"].ConnectionString.ToString());
        string sql = "SELECT Server_image_icon FROM tbl_ServerMaster WHERE server_Code = @ID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", theID);
        connection.Open();
        object theImg = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])theImg);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Just add one line in CS code

UploadImg.ImageUrl = "~/DisplayImg.ashx?id=" + code;
Sign up to request clarification or add additional context in comments.

1 Comment

I was able to fix my code by enclosing the LinkButton inside an UpdatePanel and register the button as a PostBack trigger. However, the problem that I have now is that when I download the file it returns 1 Byte of data only.
0

A PostBack from inside an UpdatePanel can only respond with the full page, as the MSAjax magic merges the old page (in the browser) and the diff generated by the PostBack to render the new version.

Convert the LinkButton to a HyperLink with all required parameters and implement an HttpHandler to serve the binary data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.