返回多个文件的 C# MVC ActionResult

标签 c# asp.net-mvc

MVC ActionResult 可以返回多个文件吗?如果是这样,它可以返回多种类型的多个文件吗?

例子:
ActionResult 能否返回 myXMLfile1.xml、myXMLfile2.xml 和 myfile3.xml?

ActionResult 可以返回 myXMLfile4.xml 和 myTXTfile1.txt 吗?

这是如何实现的?

最佳答案

您不能返回多个文件,但是,您可以将多个文件压缩到一个 .zip 文件中并返回这个压缩文件,例如,在您的项目中创建一个自定义 ActionResult,如下所示:

public class ZipResult : ActionResult
{
    private IEnumerable<string> _files;
    private string _fileName;

    public string FileName
    {
        get
        {
            return _fileName ?? "file.zip";
        }
        set { _fileName = value; }
    }

    public ZipResult(params string[] files)
    {
        this._files = files;
    }

    public ZipResult(IEnumerable<string> files)
    {
        this._files = files;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        using (ZipFile zf = new ZipFile())
        {
            zf.AddFiles(_files, false, "");
            context.HttpContext
                .Response.ContentType = "application/zip";
            context.HttpContext
                .Response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
            zf.Save(context.HttpContext.Response.OutputStream);
        }
    }

} 

然后像这样使用它:

public ActionResult Download()
{
    var zipResult = new ZipResult(
        Server.MapPath("~/Files/file1.xml"),
        Server.MapPath("~/Files/file2.xml"),
        Server.MapPath("~/Files/file3.xml")
    );
    zipResult.FileName = "result.zip";

    return zipResult;
}

在这里查看更多信息:http://www.campusmvp.net/blog/asp-net-mvc-return-of-zip-files-created-on-the-fly

关于返回多个文件的 C# MVC ActionResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17617568/

相关文章:

用于存储排列的 C# 容器

c# - DateTime.UtcNow 在不同的服务器中给出不同的值

c# - 在父 View 中显示子项的验证 asp.net mvc 3

c# - 基于用户角色批量禁用复选框 - MVC Razor

c# - 在 ASP.NET MVC 中将敏感数据从一个页面传递到另一个页面的最佳方式是什么?

c# - LINQ 时间戳 - 自动更新时间戳列?

c# - 为什么类似虚拟场的事件以 C# 中的方式工作?

c# - 更新模型的虚拟属性不起作用

jquery - 如何使用 bootstrap 或 jquery 在按钮单击时将部分 View 显示为弹出/模式?

c# - 如何对模板10的RaisePropertyChanged进行单元测试?