惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
B
Blog
V
V2EX
T
Tailwind CSS Blog
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
博客园 - 聂微东
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
The Cloudflare Blog
J
Java Code Geeks
H
Help Net Security
雷峰网
雷峰网
Apple Machine Learning Research
Apple Machine Learning Research
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Engineering at Meta
Engineering at Meta
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
D
Docker
L
LangChain Blog
人人都是产品经理
人人都是产品经理
爱范儿
爱范儿
WordPress大学
WordPress大学
V
Visual Studio Blog

博客园 - w i n s o n

Claude Code 的替代品:OpenCode — 开源免费的 AI 编程神器 CBMVC For Titanium Alloy 发布! CBMVC Titanium Framework 介绍 .Net插件框架的实现及分析(三) .Net插件框架的实现及分析(二) .Net插件框架的实现及分析(一) 在类库中调用资源文件实现国际化! Javascript下调用.Net资源文件,实现语言国际化 让 PowerDesigner 支持 SQLite! 理解依赖注入及其好处! 图文说明如何使用T4在VS2008里生成代码 Winson.Framework 3.3 发布!! Silverlight学习问题总结(一) Winson.Framework 3.2 发布!!! 通过反射自动填充实体 Winson.Framework 3.0 正式发布!! Winson.Framework 2.5 发布! Winson.SqlPager 2.5 发布! [心得]VS2008免编译立即生效的方法
使用Ajax生成的Excel文件并下載
w i n s o n · 2016-11-18 · via 博客园 - w i n s o n

2016-11-18 16:02  w i n s o n  阅读(4290)  评论()    收藏  举报

很久沒有寫文章啦,今天分享一個如何在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. 完!