Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

asp.net - Returning Multiple Files from MVC Action

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...