C#.NET后台读取服务器文件名称,并下载到本地

来源:互联网 发布:食品数据分析咨询公司 编辑:程序博客网 时间:2024/05/19 06:36

前台代码:

<asp:TemplateField HeaderText="Attachment Name">
                                    <ItemTemplate>
                                        <asp:LinkButton ID="lbtSave" runat="server" CausesValidation="False" CommandName="Save"  OnClick="btndown_Click"
                                            CommandArgument='<%#Eval("RbAttachment") %>' Text='<%#Eval("RbAttachment") %>'></asp:LinkButton>
                                    </ItemTemplate>
                     </asp:TemplateField>
  


后台代码:


  protected void btndown_Click(object sender, EventArgs e)
        {
            LinkButton bb = (LinkButton)sender;
            string filename= bb.Text;   //获取文件名称
            string dir = HttpContext.Current.Request.PhysicalApplicationPath;
            string filePath = dir + "Upload\\DocumentFiles\\"+filename;
            FileInfo DownloadFile = new FileInfo(filePath);
            //以字符流的形式下载文件  
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开  
            Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        } 

0 0
原创粉丝点击