JS download file | without refreshing download file sample code
- 2020-03-30 02:41:36
- OfStack
The background code is handler.ashx
Front-end code:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string fileName = "web.config";//File name saved by the client
string filePath = context.Server.MapPath("web.config");// The path
//Download the file as a stream of characters
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";
//Notifies the browser to download the file instead of opening it
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;
}
}
}
Front-end code:
<!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>