开发者

How to open the download window when a dynamically created link is clicked in asp.net

开发者 https://www.devze.com 2022-12-28 19:52 出处:网络
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.

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...


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>
...


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号