如何在asp.net中单击动态创建的链接时打开下载窗口

时间:2010-04-27 06:22:51

标签: c# asp.net html download

我已将txtfile存储在database.i中,当我clik链接时需要显示txtfile。并且必须动态创建此链接。

我的代码如下:

aspx代码:

 <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();
    }

我动态获得了链接,但是当我链接时我无法下载txtfile。如何实现这一目标。请帮助我...

2 个答案:

答案 0 :(得分:1)

在您的示例中,您将生成一个锚标记,其中包含指向下载 javascript函数的onclick处理程序。使用这种方法无法调用服务器端功能。

解决此问题的一种方法是write an http handler将处理下载,并将文件ID作为参数。此处理程序将使用文件ID从数据库中获取文件内容并将其写入响应:

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; }
    }
}

下一步是生成将指向先前创建的通用处理程序的锚点:

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

答案 1 :(得分:0)

首先,您尝试使用onclick处理程序调用服务器方法后面的代码,如@Darin Dimitrov指出的那样。

在你的情况下,我会使用ASP:LinkBut​​ton

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

在代码后面的事件处理程序中,我将使用Response.TransmitFile,如下所示:

 //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();

请注意,上面的代码可以传输任何文件类型,但不限于文本文件。

希望这有帮助