@Anthony Shaw的回答很好,但有两个问题:
- 如果您使用
try{} catch{}
然后在导出文件过程中出现错误会发生什么?
- 如何在保持当前页面的同时更友好地返回消息?
答案是你应该用Ajax
两个步骤来实现它:
- 您应该调用 ajax 来生成一个文件,并将该内存数据存储到
Session
orTempData
中。
阿贾克斯
$ajax({
cache: false,
url: '/Initiative/GenerateFile',
data: GenerateParams(),
success: function (data){
var response = JSON.parse(data);
if(response.IsSuccesful) {
window.location = '/Initiative/DownloadFile?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}else{
alert(response.ErrorMessage);
}
}
});
控制器
public ActionResult GenerateFile(MyParams myParams)
{
IEnumerable<Order> orders = Model.GetOrders(myparams);
if (orders.Count() == 0)
{
return new JsonResult
{
Data = new { IsSuccesful = false, ErrorMessage = "No orders" }
};
}
try
{
var pptResults = GeneratePowerpointFile(orders);
var guid = Guid.NewGuid().ToString();
TempData[guid] = pptResults.Content;
return new JsonResult
{
Data = new { IsSuccesful = true, FileGuid = guid, FileName = pptResults.FileName }
};
}
catch (Exception err)
{
return new JsonResult
{
Data = new { IsSuccesful = false, ErrorMessage = err }
};
}
}
创建一个新DownloadFile
操作来读取TempData[guid]
然后返回该文件。
[HttpGet]
public virtual ActionResult DownloadFile(string fileGuid, string fileName)
{
if (TempData[fileGuid] != null)
{
var data = TempData[fileGuid] as byte[];
return File(data, "application/vnd.ms-powerpoint", fileName);
}
else
{
return new EmptyResult();
}
}
阅读通过 AJAX MVC 下载 Excel 文件的好文章