从 MVC 操作返回多个文件 [英] Returning Multiple Files from MVC Action

查看:22
本文介绍了从 MVC 操作返回多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 MVC 3 应用程序,它有几个地方可以使用以下方法生成和返回文本文件:

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

这非常有效.现在我遇到了一种情况,我试图以类似的方式返回一对文件.在视图中,我有一个操作链接,例如单击此处获取这 2 个文件",我希望下载这两个文件,就像在上面的代码片段中下载单个文件一样.

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

推荐答案

基于 Yogendra Singh 的想法并使用 DotNetZip:

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

2019/04/10 更新:正如@Alex 所指出的,从 .NET Framework 4.5 开始就支持压缩,来自 JitBit 和其他:

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

这篇关于从 MVC 操作返回多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆