Home >Web Front-end >JS Tutorial >JS download file | no refresh download file sample code_javascript skills

JS download file | no refresh download file sample code_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:52:161356browse

Backend code Handler.ashx

Copy code The code is as follows:

<%@ WebHandler Language= "C#" Class="Handler" %>

using System;
using System.Web;

public class Handler: IHttpHandler {

public void ProcessRequest ( HttpContext context) {
string fileName = "web.config";//The file name saved by the client
string filePath = context.Server.MapPath("web.config");//Path
/ /Download files as character streams
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";
//Notify 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:
Copy code The code is as follows:




< head>



<script> <br>function download_file(url) <br>{ <br><br>if (typeof (download_file.iframe) == "undefined") <br>{ <br>var iframe = document .createElement("iframe"); <br>download_file.iframe = iframe; <br>document.body.appendChild(download_file.iframe); <br>} <br>// alert(download_file.iframe); <br> download_file.iframe.src = url; <br><br>download_file.iframe.style.display = "none"; <br><br><br><br>} <br></script>


aaaaa
bbbbb
ccccc



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn