从FileResult下载文件,而不保存到磁盘 [英] Download File from FileResult without saving to disk

查看:241
本文介绍了从FileResult下载文件,而不保存到磁盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVC 4。

I am using MVC 4.

我的控制器中有一个方法,可以根据需要生成CSV文件,然后我希望该文件由用户下载而无需将其保存到服务器端的磁盘。所以我在File()对象上传递一个MemoryStream,以避免首先将文件保存到磁盘,然后给他下载路径。

I have a method in my controller which generates a CSV file on demand and I want this file to be then downloaded by the user without the need of saving it to the disk at the server side. So I am passing a MemoryStream on the File() object to avoid having to firstly save file to disk and later give him the path for download.

控制器方法: p>

Controller Method:

[HttpGet]
public ActionResult GenerateCsv(string data)


    var sb = new StringBuilder();
    sb = GetCsvReportToString(data);

    var stream = new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString()));

    return this.File(stream, "text/csv", "ReportCsv.csv");
}

sb(StringBuilder)具有正确的数据,因为我已经调试并确认

sb (StringBuilder) has the correct data, as I have debugged it and confirmed it.

我的JavaScript代码:

my javascript code:

window.open(generateFileLink + '?data=' + dataToSend, '_blank');

事实上,窗口实际打开,出现下载对话框,但出现错误,表示不能从本地主机下载:

The window gets in fact opened, the download dialog appears but with an error, saying that it cannot be downloaded from localhost:

下载ReportToCsv中的名称不一样,因为我没有在我的问题中使用真实的名称,但并不重要。

The name is different in the download "ReportToCsv" because I didn't use real names for methods in my question, but doesn't matter.

任何人都可以帮忙吗?

Can anyone assist?

推荐答案

这个问题的答案可以在这里找到: https://stackoverflow.com/a/11267754/1417487

The answer to this question can be found here: https://stackoverflow.com/a/11267754/1417487

这是关于缓存的标题,对于IE版本6- 8。

It's a regarding the headers of cache, for IE versions 6-8.

这篇关于从FileResult下载文件,而不保存到磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆