ASP MVC下载Zip文件 [英] ASP MVC Download Zip Files
问题描述
我已经在这里我把事件的ID,然后我可以下载所有该事件的照片的图.....
这里是我的code
i have a view where i put the id of the event then i can download all the images for that event..... here's my code
[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任何想法???
The problem is that each time i get html page to download so instead of downloading "Album.zip" i get "Album.html" any ideas???
推荐答案
在MVC,而不是返回一个观点,如果你想返回一个文件,你可以返回这是一个的ActionResult
这样做:
In MVC, rather than returning a view, if you want to return a file, you can return this as an ActionResult
by doing:
return File(zipFile.GetBytes(), "application/zip", downloadFileName);
// OR
return File(zipFile.GetStream(), "application/zip", downloadFileName);
办与手动写入输出流,如果你使用MVC不乱。
Don't mess about with manually writing to the output stream if you're using MVC.
我不知道如果你能得到的字节或从的ZipFile
类流虽然。或者,您可能希望它写它的输出到的MemoryStream
,然后返回:
I'm not sure if you can get the bytes or the stream from the ZipFile
class though. Alternatively, you might want it to write it's output to a MemoryStream
and then return that:
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");
和利用这一点,你可以删除在你正在做的响应
什么都行。无需清除
或的AddHeader
。
And by using this, you can remove all lines in which you are doing anything with the Response
. No need to Clear
or AddHeader
.
这篇关于ASP MVC下载Zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!