1. 程式人生 > >c#檔案下載無響應?(已解決,記錄一下)(我使用的是MVC框架,網頁程式設計)

c#檔案下載無響應?(已解決,記錄一下)(我使用的是MVC框架,網頁程式設計)

 1.前端js

!!!我使用了form表單提交,檔案下載才有反應,還不知道原因,如果有知道的大神,麻煩透露一下哦,嘻嘻

 $("#download").click(function () {//按鈕的點選事件
            alert("aa");
            var detailid = "問題";
            var form = $("<form>");
            form.attr("style", "display:none");
            form.attr("target", "");
            form.attr("method", "post");
            form.attr("action", "/Home/DownloadModel");
            var input9 = $("<input>");
            input9.attr("type", "hidden");
            input9.attr("name", "DetailID");
            input9.attr("value", detailid);
            $("body").append(form);
            form.append(input9);
            form.submit();
            form.remove();

        });

 

 

 2.後臺控制器

   public ActionResult DownloadModel()
        {
            string detailid = Request["DetailID"];      
            if (detailid == "問題")
            {
                string fileName = "newmodel.xlsx";//客戶端儲存的檔名
                Download(fileName);
            }
            return Content("ok");
        }

    public string Download(string fileName)
        {
            string path = Server.MapPath("~/modelfile/");//工程目錄
            string filePath = path + fileName;
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
            if (!System.IO.File.Exists(filePath))
                return "下載失敗";
            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();
            return "ok";
        }