Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Multiple Files from MVC Action

Tags:

So I've got an MVC 3 application that has a couple places where a text file gets generated and returned in an action using:

return File(System.Text.Encoding.UTF8.GetBytes(someString),                  "text/plain", "Filename.extension"); 

and this works fabulously. Now i've got a situation where I'm trying to return a pair of files in a similar fashion. On the view, i have an action link like "Click here to get those 2 files" and i'd like both files to be downloaded much like the single file is downloaded in the above code snippet.

How can I achieve this? Been searching around quite a bit and haven't even seen this question posed anywhere...

like image 528
Giovanni B Avatar asked Oct 03 '12 17:10

Giovanni B


People also ask

Can we return multiple view in MVC?

You can only return one value from a function so you can't return multiple partials from one action method. If you are trying to return two models to one view, create a view model that contains both of the models that you want to send, and make your view's model the new ViewModel.

Can one action method have multiple views?

Yes, completely possible. And, it can be multiple views, or even a FileResult or other result type.

How many action methods are there in MVC?

Action Result It is a base class for all type of action results. The diagram shown below describes about abstract class of Action Result. There are two methods in Action Result. One is ActionResult() and another one is ExecuteResult().


1 Answers

Building on Yogendra Singh's idea and using DotNetZip:

var outputStream = new MemoryStream();  using (var zip = new ZipFile()) {     zip.AddEntry("file1.txt", "content1");     zip.AddEntry("file2.txt", "content2");     zip.Save(outputStream); }  outputStream.Position = 0; return File(outputStream, "application/zip", "filename.zip"); 

Update 2019/04/10: As @Alex pointed out, zipping is supported natively since .NET Framework 4.5, from JitBit and others:

using (var memoryStream = new MemoryStream()) {    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))    {       var file1 = archive.CreateEntry("file1.txt");       using (var streamWriter = new StreamWriter(file1.Open()))       {          streamWriter.Write("content1");       }        var file2 = archive.CreateEntry("file2.txt");       using (var streamWriter = new StreamWriter(file2.Open()))       {          streamWriter.Write("content2");       }    }     return File(memoryStream.ToArray(), "application/zip", "Images.zip") } 
like image 172
tocallaghan Avatar answered Sep 18 '22 15:09

tocallaghan