服务器 文件下载

文件存放路径:Project/UploadFile/Static/Download/123.xlsx

界面:
<input type="button" class="btn" value="模板下载" id="btnDownload" />

JS:
 $("#btnDownload").click(function() {

            var url = '@Url.Action("DownloadFile","OfflinePaymentManage")';

            $("#DownLoadExcela").attr("href", url);

            document.getElementById("DownLoadExcela").click();

        });

Controller:

public void DownloadFile()

        {

            string fileName = aaa.xlsx";//客户端保存的文件名     

            string path  = "~/UploadFile/Static/Download/123.xlsx";

            string filePath = Server.MapPath(path);

            //以字符流的形式下载文件     

            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();

        }

 

posted @ 2016-06-04 13:18  一代猿佬  阅读(89)  评论(0)    收藏  举报