如何在mvc应用程序中设置运行时的保存位置

时间:2013-04-11 05:46:11

标签: asp.net-mvc asp.net-mvc-3 web-applications export download

我需要在mvc应用程序中设置运行时的保存位置。在Windows应用程序中,我们使用

  

System.Windows.Forms.SaveFileDialog();

但是,我们使用Web应用程序了什么?

1 个答案:

答案 0 :(得分:2)

目前尚不清楚要保存的内容。在Web应用程序中,您可以使用文件输入将文件上载到服务器:

<input type="file" name="file" />

有关在ASP.NET MVC应用程序中上载文件的更多信息,您可以查看following post

另一方面,如果您希望用户能够从服务器下载某个文件并提示他要保存此文件的位置,则可以从控制器操作返回文件结果并指定MIME类型和文件名:

public ActionResult Download()
{
    var file = Server.MapPath("~/App_Data/foo.txt");\
    return File(file, "text/plain", "foo.txt");
}

还有File方法的其他重载,允许您动态生成文件并将其作为流传递给客户端。但是,从服务器下载文件时,在Web应用程序中理解的重要部分是Content-Disposition标头。它有两个可能的值:inlineattachment。例如,使用上面的代码,以下标题将添加到响应中:

Content-Type: text/plain
Content-Disposition: attachment; filename=foo.txt

... contents of the file ...

当浏览器从服务器收到此响应时,它将提示用户使用“另存为”对话框,允许他选择计算机上的位置来存储下载的文件。


更新:

以下是在Web应用程序中实现类似功能的方法:

public ActionResult Download()
{
    var file1 = File.ReadAllLines(Firstfilpath);
    var file2 = File.ReadAllLines(2ndfilpath);
    var mergedFile = string.Concat(file1, file2);
    return File(mergedFile, "text/plain", "result.txt");
}