一个基于src和ashx的无刷新下载文件和更新图片的方法

来源:互联网 发布:网络红包潮阅读答案 编辑:程序博客网 时间:2024/06/06 03:41

        最近在学习jQuery,使用jQuery的ajax和JSON可以较好地在ASP.NET网站前端和服务器端无刷新网页交换信息。因为网站应用系统中经常要下载Excel报表等文件,就在网上查询了无刷新下载文件的方法,该方法的关键之处有两点:

  1. 在客户端创建一个临时隐藏的iframe元素
  2. 将ashx文件的url赋给Iframe的src属性

以下为客户端html文件,其中http://localhost/json为.net 2.0网站的虚拟路径。

<html><head><script type="text/javascript">function download(){    DownloadFileByIframe("http://localhost/json/download.ashx"); }function DownloadFileByIframe(url){    var iframe = document.getElementById("TempCreatedIframeElement");    if(iframe == null)    {    iframe = document.createElement("iframe");    iframe.id = "TempCreatedIframeElement";    }    iframe.style.display = "none";    document.body.appendChild(iframe);    iframe.src = url;}</script></head><body><input type="button" value="donwload" onclick="download()" /></body></html>

以下为ashx文件,仅以一个字符串代表文件(实际使用时可以读取一个文件)。

<%@ WebHandler Language="C#" Class="download" %>using System;using System.Web;public class download : IHttpHandler {        public void ProcessRequest (HttpContext context)     {        context.Response.Clear();        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + "abc.txt");        context.Response.ContentEncoding = System.Text.Encoding.Default;        context.Response.ContentType = "text/plain";        context.Response.Write("abcd");        context.Response.Flush();        context.Response.Close();    }     public bool IsReusable     {        get         {            return false;        }    }}

        常见的window.open(url)方式下载一个文件,有窗口打开等动作,屏幕虽然不刷新,但有晃动。显然,上述方法的用户体现效果要自然些。

        有src属性的html元素还有图片img。使用上面类似的方法:在ashx中返回图片文件(二进制格式)给img的src,可以做到无刷新地更新客户端的图片。

0 0
原创粉丝点击