Asp.net網站中 js通過iframe下載文件

1. 前臺代碼

 <iframe id="exportIFrame" style="display: none;"></iframe>
 //ajax代碼
 <script type="text/javascript">
   $.ajax({
            url: "test.ashx?method=downFile&ID=" + ID + "",
            type: "Post",
            data: {},
            error: function (jqXHR, textStatus, errorThrown) {
                mini.alert(jqXHR.responseText, "信息提示");
            },
            success: function (data) {
                if (data == "no") {
                    alert("文件在目錄中不存在!");
                } else {
                    var url = "test.ashx?method=downFile&ID=" + ID + "";
                    var exportIFrame = document.getElementById("exportIFrame");
                    exportIFrame.src = url;
                }

            }
        });
 </script>

2.後臺代碼

 private object downFile(HttpContext context)
        {
            try
            {
                string ID = context.Request["ID"];
                testBLL bll = new testBLL();
                //獲取文件信息
                DataTable dt = bll.downFile(ID);
                if (dt == null)
                {
                    return "no";
                }
                else
                {
                    string path = HttpContext.Current.Server.MapPath("../Reports/file/") + dt.Rows[0]["FJNAME"].ToString();
                    if (File.Exists(path))
                    {
                        System.IO.FileInfo file = new System.IO.FileInfo(path);
                        context.Response.Clear();
                        context.Response.ClearHeaders();
                        context.Response.Buffer = false;
                        context.Response.ContentType = "application/octet-stream";
                        //新的名字+擴展名,HttpUtility.UrlEncode保證下載文件名非亂碼
                        context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(dt.Rows[0]["title"].ToString() + "." + dt.Rows[0]["kuozhanming"].ToString(), System.Text.Encoding.UTF8));
                        context.Response.AppendHeader("Content-Length", file.Length.ToString());
                        context.Response.WriteFile(file.FullName);
                        context.Response.Flush();
                        context.Response.End();
                        return "";
                    }
                    else
                    {
                        return "no";
                    }
                }             

            }
            catch (Exception)
            {
                return "no";
            }            
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章