gpt4 book ai didi

asp.net-mvc - ASP MVC 下载 Zip 文件

转载 作者:行者123 更新时间:2023-12-05 08:28:15 24 4
gpt4 key购买 nike

我有一个 View ,我可以在其中放置事件的 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”,有什么想法吗???

最佳答案

在 MVC 中,如果您想返回一个文件,而不是返回一个 View ,您可以通过执行以下操作将其作为 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

关于asp.net-mvc - ASP MVC 下载 Zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15385958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com