HTML:
<table> <tr> <td> 下载导入模板 </td> <td> <asp:LinkButton ID="lkbtn" runat="server" OnClick="lkbtn_Click">人才档案模板下载</asp:LinkButton> </td> </tr> </table>
下载按钮click事件:
protected void lkbtn_Click(object sender, EventArgs e) { DownLoadFile(Server.MapPath("~/App_Data/人才档案模板.xls"), "人才档案模板.xls"); }
下载函数:
/// <summary> /// 下载附件 /// </summary> /// <param name="filepath">文件路径(包括文件名)</param> /// <param name="filename">文件名</param> public void DownLoadFile(string filepath, string filename) { if (!System.IO.File.Exists(filepath)) { JScript.AlertAfterLoad("未找到文件!"); return; } System.IO.FileStream iStream = null; byte[] buffer = new Byte[10000]; int length; long dataToRead; try { iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); dataToRead = iStream.Length; Response.AddHeader("Connection", "Keep-Alive"); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename)); while (dataToRead > 0) { if (Response.IsClientConnected) { length = iStream.Read(buffer, 0, 10000); Response.OutputStream.Write(buffer, 0, length); Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { dataToRead = -1; } } } catch (Exception) { JScript.AlertAfterLoad("文件读取错误!"); } finally { if (iStream != null) { iStream.Close(); } } }