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