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
有疑问或不懂的同学可以去这里用一下就明白了
a标签ajax直接调用后台方法下载文件:_第1张图片

如有问题,请加我QQ:631931078或352167311

你可能感兴趣的:(jquery,.net,asp.net)