using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; #region histroy ///程式代號:OpenFile ///程式名稱:檔案下載 ///程式說明: ///xx.YYYY/MM/DD VER AUTHOR COMMENTS(說明修改的內容) ///01.2012/05/10 1.0 Ethan CREATE #endregion namespace OT.Web { public partial class OpenFile : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // 在這裡放置使用者程式碼以初始化網頁 Response.Expires = 0; FnOpenFile(); } private void FnOpenFile() { try { //防止在IE中直接開啟本程式操作檔案 if (Request["U"] == null && Session["U"] == null) { WriteMsg("非法登入,不可操作檔案!"); } //重定向後開啟檔案 else if (Session["U"] != null) { string strFileName = Session["U"].ToString(); Session.Remove("U");//及時釋放Session this.ReadFile(strFileName); } //遠端呼叫本程式時帶入參數檔案名稱U,為防止User看到U的內容,進行一次重定向 else if (Request["U"] != null) { string strFileName = Request.QueryString["U"].ToString(); strFileName = FnHidToFileName(strFileName).Replace("\\", "/"); //Session["U"] = strFileName;//用Session記錄U做重定向動作 //Session["FileName"] = Request.QueryString["FileName"].ToString(); //Response.Redirect(@"OpenFile.aspx", false); this.ReadFile(strFileName); } } catch (Exception ex) { Session.Remove("U");//及時釋放Session this.WriteMsg("開啟檔案出錯,請重新試一次!"); } } /// /// 將用於URL中傳參的Base64碼轉為String,轉換前將Base64碼中用*和@替換的+和/還原 /// /// /// public string FnHidToFileName(string strFrom) { string strTo = strFrom.Replace("*", "+").Replace("@", "/").Replace("!", "="); strTo = FnBase64ToString(strTo); return strTo; } /// /// 將Base64碼轉為String /// /// /// public string FnBase64ToString(string strFrom) { byte[] byTo = Convert.FromBase64String(strFrom); string strTo = System.Text.Encoding.Default.GetString(byTo); return strTo; } /// /// 開啟檔案 /// /// private void ReadFile(string strFileName) { string strDownFileName = UTF_FileName(Request.QueryString["FileName"].ToString()); strDownFileName = HttpUtility.UrlEncode(strDownFileName, System.Text.Encoding.UTF8); //解決中文問題 Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition" , String.Format("attachment; filename=\"{0}\";", strDownFileName)); //Response.Write("**" + fileName); Response.WriteFile(UTF_FileName(strFileName)); try { Response.End(); //如果提前結束會出現異常。 } catch (Exception ex) { return; } } private static string UTF_FileName(string filename) { return HttpUtility.UrlDecode(filename); //return HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8); } /// /// Alert訊息並關閉畫面 /// /// alert出來的訊息內容 private void WriteMsg(string Msg) { StringBuilder sbScript = new StringBuilder(); sbScript.Append(""); this.ClientScript.RegisterStartupScript(GetType(), "close", sbScript.ToString()); } } }