Ajax实现下载文件功能

刚开始学习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;
            }
        }
    }
}

    原文作者:Karl Du
    原文地址: https://blog.csdn.net/dumiaoxin/article/details/80735809
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞