a標籤ajax直接調用後臺方法下載文件:

個人原創小說網站:友書–綠色純淨無廣告,歡迎大家前來指點

a標籤ajax直接調用後臺方法下載文件:
—-前臺:

<p id="TrueData" style="margin-top: 10px;"><a href="../program/ashx/DownTemplate.ashx">下載空白模板</a>,並按模板填寫文件後上傳</p>

—-後臺:

             public void ProcessRequest(HttpContext context)
             {
                context.Response.ContentType = "text/json";
                context.Response.Buffer = true;
                context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
                context.Response.AddHeader("pragma", "no-cache");
                context.Response.AddHeader("cache-control", "");
                context.Response.CacheControl = "no-cache";
                string url = "上傳模版.xls";
                FileHelper.DownloadFile(url);
            }

         public static void DownloadFile(string FileUrl)
         {
            string filePath = path + FileUrl;//路徑
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
            if (fileInfo.Exists == true)
              {
                const long ChunkSize = 102400;//100K 每次讀取文件,只讀取100k,這樣可以緩解服務器的壓力
                byte[] buffer = new byte[ChunkSize];
                System.Web.HttpContext.Current.Response.Clear();
                System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
                long dataLengthToRead = iStream.Length;//獲取下載的文件總大小
                System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
                System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                while (dataLengthToRead > 0 && System.Web.HttpContext.Current.Response.IsClientConnected)
                {
                    int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//讀取的大小
                    System.Web.HttpContext.Current.Response.OutputStream.Write(buffer, 0, lengthRead);
                    System.Web.HttpContext.Current.Response.Flush();
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                //System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
                System.Web.HttpContext.Current.Response.End();
                System.Web.HttpContext.Current.Response.Close();

            }
        }

ps:其實還有種更簡單的辦法,直接用h5, a標籤上在加一個屬性就完美解決下載問題,不用寫後臺繁瑣的文件流代碼,具體實列如下:

<a href="/Upload/20170608/201706081350129077.xls" download="test.xls">文件下載</a>

download裏面填寫的是你要下載文件的文件名,舉例:如果你要下的文件名爲:test.xls,而你在服務器上存的真實文件名爲:123456.xls,如果download中填寫test,那麼下載下來的文件名就叫test.xls而不是123456.xls,download中不管你填不填寫,文件都會被下載下來,區別只是下載下來的文件的文件名不同而已

w3school在線測試地址:
http://www.w3school.com.cn/tiy/t.asp?f=html_a_download
有疑問或不懂的同學可以去這裏用一下就明白了
這裏寫圖片描述

如有問題,請加我QQ:631931078或352167311

發佈了37 篇原創文章 · 獲贊 6 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章