JS下载文件|无刷新下载文件示例代码

2019-12-21,,,

后台代码Handler.ashx
复制代码 代码如下:
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
string fileName = "web.config";//客户端保存的文件名
string filePath = context.Server.MapPath("web.config");//路径
//以字符流的形式下载文件
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
context.Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}

public bool IsReusable {
get {
return false;
}
}

}

前端代码:
复制代码 代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<title></title>
<script>
function download_file(url)
{

if (typeof (download_file.iframe) == "undefined")
{
var iframe = document.createElement("iframe");
download_file.iframe = iframe;
document.body.appendChild(download_file.iframe);
}
// alert(download_file.iframe);
download_file.iframe.src = url;

download_file.iframe.style.display = "none";

}
</script>
</head>
<body>
<a href="javascript:void(0);" onclick="download_file('Handler.ashx')">aaaaa</a>
<a href="javascript:void(0);" onclick="download_file('Handler.ashx')">bbbbb</a>
<a href="javascript:void(0);" onclick="download_file('Handler.ashx')">ccccc</a>

</body>
</html>

您可能感兴趣的文章:

  • php+js实现的无刷新下载文件功能示例
  • 通过JavaScript下载文件到本地的方法(单文件)
  • JavaScript实现的浏览器下载文件的方法
  • js下载文件并修改文件名
  • 使用JS代码实现点击按钮下载文件
  • 用JS在浏览器中创建下载文件
  • JAVASCRIPT模式窗口中下载文件无法接收iframe的流
  • js自动下载文件到本地的实现代码
  • 使用 JavaScript 创建并下载文件(模拟点击)

《JS下载文件|无刷新下载文件示例代码.doc》

下载本文的Word格式文档,以方便收藏与打印。