ASP MVC Download Zip Files

I have a view where I put the event id, then I can upload all the images for this event ..... here is 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();
        }
    }

The problem is that every time I get an html page to download, instead of downloading "Album.zip", I get "Album.html" any ideas ???

+1
source share
1 answer

In MVC, instead of returning a view, if you want to return a file, you can return it as ActionResultby doing:

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

Do not argue with manual recording in the output stream if you use 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. Clear AddHeader.

+9

Source: https://habr.com/ru/post/1584998/


All Articles