【问题标题】:ASP MVC Download Zip FilesASP MVC 下载 Zip 文件
【发布时间】:2013-03-13 12:55:25
【问题描述】:

我有一个视图,我在其中放置了事件的 ID,然后我可以下载该事件的所有图像..... 这是我的代码

[HttpPost]
    public ActionResult Index(FormCollection All)
    {
        try
        {
            var context = new MyEntities();

            var Im = (from p in context.Event_Photos
                      where p.Event_Id == 1332
                      select p.Event_Photo);

            Response.Clear();

            var downloadFileName = string.Format("YourDownload-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH_mm_ss"));
            Response.ContentType = "application/zip";

            Response.AddHeader("content-disposition", "filename=" + downloadFileName);

            using (ZipFile zipFile = new ZipFile())
            {
                zipFile.AddDirectoryByName("Files");
                foreach (var userPicture in Im)
                {
                    zipFile.AddFile(Server.MapPath(@"\") + userPicture.Remove(0, 1), "Files");
                }
                zipFile.Save(Response.OutputStream);

                //Response.Close();
            }
            return View();
        }
        catch (Exception ex)
        {
            return View();
        }
    }

问题是每次我下载 html 页面时,我都没有下载“Album.zip”,而是得到“Album.html”任何想法???

【问题讨论】:

  • 调试以检查downloadFileName是否包含.zip扩展..
  • 它包含 .zip 这是其中的内容“YourDownload-2013-03-13-15_04_20.zip”

标签: asp.net-mvc dotnetzip


【解决方案1】:

在 MVC 中,如果您想返回一个文件,而不是返回一个视图,您可以通过以下方式将其返回为 ActionResult

return File(zipFile.GetBytes(), "application/zip", downloadFileName);
// OR
return File(zipFile.GetStream(), "application/zip", downloadFileName);

如果您使用的是 MVC,请不要纠结于手动写入输出流。

我不确定您是否可以从 ZipFile 类中获取字节或流。或者,您可能希望它将其输出写入MemoryStream,然后返回:

 var cd = new System.Net.Mime.ContentDisposition {
     FileName = downloadFileName,
     Inline = false, 
};
Response.AppendHeader("Content-Disposition", cd.ToString());
var memStream = new MemoryStream();
zipFile.Save(memStream);
memStream.Position = 0; // Else it will try to read starting at the end
return File(memStream, "application/zip");

通过使用它,您可以使用Response 删除您正在执行任何操作的所有行。无需ClearAddHeader

【讨论】:

  • 我只在我的代码中将“application/zip”替换为“application/octet-stream”时才工作。 zipFile.GetBytes() 也给出错误
  • 我还有一个问题,不,.zip 文件包含文件的整个路径,我只想将图像放在 zip 文件中?我怎么能这样做??
  • 我不知道 DotNetZip 库的细节,这就是我在回答中所说的,这也是我添加第二个解决方案的原因(将其写入 MemoryStream 并返回)。我将添加一行来强制下载而不是内联。
  • 关于文件路径,请随时在此站点上打开一个单独的问题。
  • 我相信仍然不需要ContentDisposition。它将作为文件而不是页面提供,因此用户浏览器不应该只将其显示为页面。尤其是 "application/zip" 作为内容类型。 (但是您必须将文件名添加到对 File 的调用中才能显示正确的名称)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多