zoukankan      html  css  js  c++  java
  • 使用Ajax生成的Excel文件并下載

    很久沒有寫文章啦,今天分享一個如何在ASP.NET MVC里使用Ajax下載生成文件的方法,以下只是個人心得:
     
    大家都應該知道,在ASP.NET MVC里,如果通過Ajax調用后臺控制器時,可以返回一個JSON對象,但并不能直接返回文件(除非刷新頁面,那就不是Ajax啦),所以如果想用Ajax生成文件并下載的話,那只要將生成的文件先保存到服務器上,然後再將文件路徑通過JSON返回,之後才可以進行下載,當然由於是暫時性存放,所以當下載完后就需要馬上刪除相應的文件。
     
    以下是做法以動態生成Excel為例(生成Excel的具體步驟我就省略了,這并不是此文章的重點):
     
    1. 首先創建Action生成Excel文件
    [HttpPost]
    public JsonResult ExportExcel()
    {
        DataTable dt = DataService.GetData();
        var fileName = "Excel_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls";
        //將生成的文件保存到服務器的臨時目錄里
        string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName);
     
        using (var exportData = new MemoryStream())
        {
            //如何生成Excel這里就不詳細說明啦,我這里對Excel的操作使用的是 NPOI
            Utility.WriteDataTableToExcel(dt, ".xls", exportData);
     
            FileStream file = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
            exportData.WriteTo(file);
            file.Close();
        }
     
        var errorMessage = "you can return the errors in here!";
     
        //返回生成的文件名
        return Json(new { fileName = fileName, errorMessage = "" });
    }
     
    2. 創建下載用的 Action
    [HttpGet]
    [DeleteFileAttribute] //Action Filter, 下載完后自動刪除文件,這個屬性稍後解釋
    public ActionResult Download(string file)
    {
        //到服務器臨時文件目錄下載相應的文件
        string fullPath = Path.Combine(Server.MapPath("~/temp"), file);
        //返回文件對象,這里用的是Excel,所以文件頭使用了 "application/vnd.ms-excel"
        return File(fullPath, "application/vnd.ms-excel", file);
    }
     
    3. 由於要做到下載完后自動刪除文件,所以再創建一個 Action Filter 
    public class DeleteFileAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Flush();
            //將當前filter context轉換成具體操作的文件并獲取文件路徑
            string filePath = (filterContext.Result as FilePathResult).FileName;
            //有文件路徑后就可以直接刪除相關文件了
            System.IO.File.Delete(filePath);
        }
    }
     
    4. 最后在前臺添加 Ajax 調用的代碼:
    //這里我使用了 blockUI 做loading...
    $.blockUI({ message: '<h3>Please wait a moment...</h3>' });    
    $.ajax({
        type: "POST",
        url: '@Url.Action("ExportExcel","YourController")', //調用相應的controller/action
        contentType: "application/json; charset=utf-8",
        dataType: "json",
    }).done(function (data) {
        //console.log(data.result);
        $.unblockUI();
        //接收返回的文件路徑,此文件這時已保存到服務器上了
        if (data.fileName != "") {
            //通過調用 window.location.href 直接跳轉到下載 action 進行文件下載操作
            window.location.href = "@Url.RouteUrl(new { Controller = "YourController", Action = "Download"})/?file=" + data.fileName;
        }
    });
     
    5. 完!
  • 相关阅读:
    office excel无法打开超链接解决方法
    mysql默认的数据库介绍(还没看,找时间研究)
    mysql目录结构及配置文件
    springboot-actuator应用后台监控
    服务器端负载均衡和客户端负载均衡的区别
    Spring Cloud Eureka 自我保护机制
    HDU 4028 The time of a day (dp+离散化)
    HDU 3652 B-number(数位DP)
    HDU 2966 In case of failure
    HDU 3622 Bomb Game
  • 原文地址:https://www.cnblogs.com/winsonet/p/6078070.html
Copyright © 2011-2022 走看看