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...
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.
Yes, completely possible. And, it can be multiple views, or even a FileResult or other result type.
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().
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") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With