C # MVC ActionResult that returns multiple files

Can MVC ActionResult return multiple files? If so, can it return multiple files with multiple types?

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

Can ActionResult return myXMLfile4.xml and myTXTfile1.txt?

How can I do that?

+4
source share
1 answer

You cannot return multiple files, but you can compress several files in a .zip file and return this compressed file, for example, create your own ActionResult project in your project, for example:

 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 as follows:

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

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

+5
source

Source: https://habr.com/ru/post/1491138/


All Articles