asp.net 中 linkbutton 点击下载文件



1、下载功能:


 <asp:LinkButton ID="lbtnAttachName" runat="server" ToolTip="下载文件" Text='<%#Eval("AttachName") %>'
     PostBackUrl='<%#Eval("attachPath","~/Common/FileDown.aspx?path={0}") %>'></asp:LinkButton>


FileDown.aspx.cs 文件
 protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string path = Request.QueryString["path"];


            string filePath = Server.MapPath("~/" + Server.UrlDecode(path));
            if (!File.Exists(filePath))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('文件不存在!'); history.back(); ", true);
                return;
            }
            new FileInfo(filePath).Attributes = FileAttributes.Normal;
            FileStream r = new FileStream(filePath, FileMode.Open);
            //设置基本信息 
            Response.Buffer = false;
            Response.AddHeader("Connection", "Keep-Alive");
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName(filePath));
            Response.AddHeader("Content-Length", r.Length.ToString());
            while (true)
            {
                //开辟缓冲区空间 
                byte[] buffer = new byte[1024];
                //读取文件的数据 
                int leng = r.Read(buffer, 0, 1024);
                if (leng == 0)//到文件尾,结束 
                    break;
                if (leng == 1024)//读出的文件数据长度等于缓冲区长度,直接将缓冲区数据写入 
                    Response.BinaryWrite(buffer);
                else
                {
                    //读出文件数据比缓冲区小,重新定义缓冲区大小,只用于读取文件的最后一个数据块 
                    byte[] b = new byte[leng];
                    for (int i = 0; i < leng; i++)
                        b[i] = buffer[i];
                    Response.BinaryWrite(b);
                }
            }
            r.Close();//关闭下载文件 
            Response.End();//结束文件下载


        }
        catch (Exception)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "alert('文件下载时出现错误!'); history.back(); ", true);
              
           // Alert(this, "文件下载时出现错误!");
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值