欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

实现ASP.NET无刷新下载并提示下载完成的开发思路

程序员文章站 2023-10-31 13:58:28
先给大家贴代码了,后面给大家在做具体的文字说明。 以下是前端代码: <%@ page language="c#" autoeventwireup="tru...

先给大家贴代码了,后面给大家在做具体的文字说明。

以下是前端代码:

<%@ page language="c#" autoeventwireup="true" codebehind="webform2.aspx.cs" inherits="webapplication1.webform2" %>
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  <title></title>
  <script src="scripts/jquery-1.8.2.js"></script>
  <script type="text/javascript">
    $(function () {
      $("#btndownload").on("click", function () {
        var $loading = $("#loadingbox");
        var downid = new date().gettime() + "-" + math.random();
        $loading.css("display", "block");
        download($("#downfile").val(), downid);
        var tid=setinterval(function () {
          $.post("webform2.aspx", { getresult: "y", downid: downid }, function (result) {
            //document.writeln("result:" + result);
            if(result=="y")
            {
              clearinterval(tid);
              $loading.css("display", "none");
              alert("下载完成!");
            }
          });
        }, 3000);
      });
      function download(filename,downid) {
        var $form = $("<form target='' method='post' action='webform2.aspx'></form>");
        $form.append("<input type='hidden' name='filename' value='" + filename + "'>");
        $form.append("<input type='hidden' name='downid' value='" + downid + "'>");
        $('body').append($form);
        $form.submit();
      }
    });
  </script>
</head>
<body>

    要下载的文件名:<input type="text" id="downfile" />

 <input type="button" id="btndownload" value="无刷新下载文件" />
  <div id="loadingbox" style="display:none;">
    正加下载中,请稍候。。。
  </div>
</body>
</html>

以下是服务器端代码:

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using system.io;
namespace webapplication1
{
  public partial class webform2 : system.web.ui.page
  {
    protected void page_load(object sender, eventargs e)
    {
      if (request.httpmethod == "post")
      {
        string getresult = request.form["getresult"];
        string downid=request.form["downid"];
        string cachekey =string.format("downloadcompleted-{0}-{1}",downid,request.userhostaddress);
        if (getresult == "y") //判断是否为获取下载结果的请求
        {
          string result = (cache[cachekey] ?? "n").tostring();
          response.clear();
          response.write(result);
          if(result=="y") //如果查询到下载完成,则应清除标记下载完成的cache
          {
            cache.remove(cachekey);
          }
          response.end();
          return;
        }
        string filename = request.form["filename"];
        string localfilepath = server.mappath("~/" + filename);
        system.io.fileinfo file = new system.io.fileinfo(localfilepath);
        response.clear();
        response.clearheaders();
        response.buffer = false;
        response.addheader("content-disposition", "attachment;filename=" + file.name);
        response.addheader("content-length", file.length.tostring());
        response.contenttype = "application/octet-stream";
        response.writefile(file.fullname);
        response.flush();
        cache.insert(cachekey, "y");//输出所有文件数据后,添加cache,并设置downloadcompleted=y,供页面查询结果使用
        response.end();
      }
    }
  }
}

实现原理:前端通过动态创建form用来请求下载的资源,请求参数中必需包含一个downid(我这里还包含了一个要下载的文件名),这个是与服务器端的cache key相对应的,服务器端接收到下载请求后,会获取下载的文件名及downid,然后依据downid生成一个相对应的cache key用于标识下载结果,再依据下载文件名获取服务器的文件资源并响应输出文件流供客户端下载,输出完毕后,生成一个cache,并标记为y,表明已输出完毕。客户端在下载文件的同时,会每隔3秒请求服务器获取下载完成的cache标识,若获取到其值为y,则表明下载完成,服务器立即清除该cache,客户端作出相应的响应(比如:关闭提示下载的对话框及弹出下载完成的对话框)

效果如下:

 实现ASP.NET无刷新下载并提示下载完成的开发思路

经过多个不同的浏览器及大文件压力测试,兼容性良好,都能正常下载并能收到下载完成提示,基于以上原理,可以实现进度条显示,实现原理简述:客户端请求服务器下载资源-->服务器响应并按字节分段依次输出,每次输出时生成cache,并保存输出进度,直至全部输出完毕,客户端在请求服务器下载资源的同时,也需要同时每隔几秒请求查询服务器下载进度,直至下载进度为100%停止请求。也可利用html5新特性websocket技术来实现。