ASP.net MVC 返回文件和重定向 [英] ASP.net MVC Return File and Redirect
本文介绍了ASP.net MVC 返回文件和重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个返回 csv 文件的控制器.我想在显示后重定向到一个动作,即返回主视图.控制器逻辑如下图所示:
I have a controller that returns csv file. I want to redirect to an action after this has displayed, i.e. return to the home view. The controller logic is shown below:
public ActionResult DownloadCSV(string fileName)
{
string csv;
using (StreamReader sr = new StreamReader(fileName))
{
csv = sr.ReadToEnd();
}
return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Export.csv");
}
推荐答案
简而言之,由于 HTTP 限制,您无法在同一操作中强制下载和重定向文件.但是您可以通过使用 window.open
打开文件下载操作来强制下载.
The short version is that you can't force a file download and redirect in the same action because of HTTP limitations. But you could force the download by opening the file-download action using window.open
.
示例:
<a href="Action/RedirectPage" data-file="Action/DownloadCVS" class="file-download">Download File</a>
<script>
$(function() {
$('a.file-download').click(function() {
window.open($(this).data('file'));
});
});
</script>
在本例中,我使用了 HTML5 属性,但您不仅限于这种方式.
In this case I used HTML5 attributes, but you're not limited to do it in this way.
这篇关于ASP.net MVC 返回文件和重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文