Skip to content

Instantly share code, notes, and snippets.

@pavoldecky
Created March 3, 2016 18:23
Show Gist options
  • Save pavoldecky/9c8d25589f1b0c51369c to your computer and use it in GitHub Desktop.
Save pavoldecky/9c8d25589f1b0c51369c to your computer and use it in GitHub Desktop.
Create ZIP file from files uploaded in ASP.NET MVC
[HttpPost]
public ActionResult Upload(UploadModel model, IEnumerable<HttpPostedFileBase> files)
{
try
{
var guid = Guid.NewGuid();
if (files != null && files.Any())
{
using (var ms = new MemoryStream())
{
using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
foreach (var attachment in files)
{
var entry = zipArchive.CreateEntry(attachment.FileName, CompressionLevel.Fastest);
using (var entryStream = entry.Open())
{
attachment.InputStream.CopyTo(entryStream);
}
}
}
string folder = Server.MapPath("~/uploads/");
string fileName = string.Format("{0}.zip", guid);
string path = Path.Combine(folder, fileName);
using (FileStream file = new FileStream(path, FileMode.Create, System.IO.FileAccess.Write))
{
ms.Position = 0;
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
file.Write(bytes, 0, bytes.Length);
ms.Close();
}
}
}
}
catch (Exception ex)
{
}
return RedirectToAction("Index");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment