views:

118

answers:

2

i have stored the txtfile in the database.i need to show the txtfile when i clik the link. and this link has to be created dynamically.

my code below:

aspx code:

 <div id="divlink" visible="false" runat="server">
                    </div>

aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            DataTable dtassignment = new DataTable();  

            dtassignment = serviceobj.DisplayAssignment(Session["staffname"].ToString());

                if (dtassignment != null)
                {
                    Byte[] bytes = (Byte[])dtassignment.Rows[0]["Data"];
                    //download(dtassignment);
                }
                divlink.InnerHtml = "";
                divlink.Visible = true;
                foreach (DataRow r in dtassignment.Rows)
                {
                    divlink.InnerHtml += "<a href='" + 
                            "'onclick='download(dtassignment)'>" + 
                             r["Filename"].ToString() + "</a>" + "<br/>";
                }
         }
    }

-

    public void download(DataTable dtassignment)
    {
        System.Diagnostics.Debugger.Break();

        Byte[] bytes = (Byte[])dtassignment.Rows[0]["Data"];

        Response.Buffer = true;

        Response.Charset = "";

        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        Response.ContentType = dtassignment.Rows[0]["ContentType"].ToString();

        Response.AddHeader("content-disposition", "attachment;filename="

        + dtassignment.Rows[0]["FileName"].ToString());

        Response.BinaryWrite(bytes);

        Response.Flush();

        Response.End();
    }

i have got the link dynamically, but i did not able to download the txtfile when i clik the link. how to carry out this. pls help me out...

A: 

In your sample you are generating an anchor tag that has an onclick handler pointing to the download javascript function. You cannot call a server side function with this approach.

One way to solve this is to write an http handler that will handle the download given the file id as parameter. This handler will use the file id to fetch the file contents from the database and write it to the response:

public class Download : IHttpHandler
{
    public void ProcessRequest(System.Web.HttpContext context)
    {
        // read the file name passed in the request
        string fileid = context.Request["fileid"];
        string fileContents = GetFileFromStore(fileid);
        var response = context.Response;
        response.ContentType = "text/plain";
        response.AddHeader("content-disposition", "attachment;filename=abc.txt"); 
        response.Write(fileContents);
    }

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

The next step is to generate the anchors that will point to the generic handler previously created:

<a href="/download.ashx?fileid=1">Download file 1</a>
<a href="/download.ashx?fileid=2">Download file 2</a>
<a href="/download.ashx?fileid=3">Download file 3</a>
...
Darin Dimitrov
Thanks for your reply...but this did we have to place this <a> tag manually??? , i need the links to generated dynamically for the user whom i pass in session. this user can have 2 or 3 or 4.... etc.. txtfiles.
Ranjana
When then use a loop and generate the links dynamically.
Darin Dimitrov
A: 

First of all you are trying to call a code behind server method using the onclick handler as @Darin Dimitrov pointed out.

In your case I would an ASP:LinkButton

<asp:LinkButton ID="lnkBtnDownload"runat="server "OnClick="lnkBtnDownload_Click"/>

And in the event handler in code behind I would use the Response.TransmitFile like this:

 //get the Temp internet folder path
 string filePath = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + "\\" + YourFileName;
 //save the file on the server
 FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
 fs.Write(YourByteArray, 0, YourByteArray.Length);
 fs.Close();

 //transmit the file
 Response.ContentType = "application/octet-stream";
 Response.AppendHeader("Content-Disposition", "attachment; filename=" + YourFileName);

 Response.TransmitFile(filePath);
 Response.End();

Note that the code above can transmit any file type and is not limited to text files.

Hope this helps

Fahad
thank u friend... i need to know how to create the linki.e<asp:LinkButton ID="lnkBtnDownload"runat="server "OnClick="lnkBtnDownload_Click"/>dynamically for each record fetch from database instead of placing the static linkbutton
Ranjana
Check out this article on code project, it will help youhttp://www.codeproject.com/KB/aspnet/DownloadAssistant.aspx
Fahad