Ajax實現下載檔案功能
阿新 • • 發佈:2019-01-23
剛開始學習Asp的時候我們實現下載功能可能是這樣
<form id="form1" runat="server">
ASP:<asp:Button runat="server" ID="btn2" Text="下載檔案" OnClick="btn2_onclick"/>
</form>
protected void btn2_onclick(object sender, EventArgs e) { string fileName = "test.txt"; string filePath = HttpContext.Current.Server.MapPath("~/" + fileName); if (File.Exists(filePath)) { Response.ContentType = "application/unknow"; Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName + ""); Response.TransmitFile(filePath); } }
後來想用Ajax,於是開始動手做
<div>
Ajax: <input type="button" id="btn1" value="下載檔案"/>
</div>
<script src="jquery.min.js"></script> <script> $(document).ready(function () { $('#btn1').click(function () { $.post("HandlerDownFile.ashx", { fileName: 'test.txt' }) }); }) </script>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; namespace WebApplication1 { /// <summary> /// HandlerDownFile 的摘要說明 /// </summary> public class HandlerDownFile : IHttpHandler { public void ProcessRequest(HttpContext context) { try { string fileName = context.Request["fileName"]; string filePath = context.Server.MapPath("~/" + fileName); if (File.Exists(filePath)) { context.Response.ContentType = "application/unknow"; context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName + ""); context.Response.TransmitFile(filePath); } } catch (IOException ex) { throw new Exception(ex.Message,ex); } finally { context.Response.Close(); } } public bool IsReusable { get { return false; } } } }
然後發現問題來了,我返回的資料流前端沒接頭人,那怎麼儲存?
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DownFile.aspx.cs" Inherits="WebApplication1.login" %>
<!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="jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#btn1').click(function () {
var xhr = new XMLHttpRequest();
xhr.open("POST", "HandlerDownFile.ashx?fileName=test.txt", true);
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status == 200) {
var blob = this.response;
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function (e) {
var a = document.createElement('a');
a.download = "test.txt";
a.href = e.target.result;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
};
xhr.send();
});
})
</script>
</head>
<body>
<div>
Ajax: <input type="button" id="btn1" value="下載檔案"/>
</div>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace WebApplication1
{
/// <summary>
/// HandlerDownFile 的摘要說明
/// </summary>
public class HandlerDownFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
string fileName = context.Request["fileName"];
string filePath = context.Server.MapPath("~/" + fileName);
if (File.Exists(filePath))
{
FileStream fs = new FileStream(filePath, 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=" + fileName + "");
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
}
catch (IOException ex)
{
throw new Exception(ex.Message,ex);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}