A Bogus
A Bogus

Reputation: 3930

C# MVC ActionResult that returns multiple files

Can an MVC ActionResult return multiple files? If so, can it return multiple files, of multiple type?

Examples:
Can an ActionResult return myXMLfile1.xml, myXMLfile2.xml, and myfile3.xml?

Can an ActionResult return myXMLfile4.xml, and myTXTfile1.txt?

How could this be accomplished?

Upvotes: 5

Views: 8893

Answers (1)

Felipe Oriani
Felipe Oriani

Reputation: 38608

You cannot return multiples files, but, you can compact multiple files in a .zip file and return this compacted file, for sample, create a custom ActionResult in your project, like this:

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);
        }
    }

} 

And use it like this:

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;
}

See more here: http://www.campusmvp.net/blog/asp-net-mvc-return-of-zip-files-created-on-the-fly

Upvotes: 5

Related Questions