使用ASP.NET MVC中的ZIP文件

由于ASP.NET 4.5,可以从.NET Framework中的类完成zipping和解压缩文件。尽管如此,几乎所有示例都可以说明在ASP.NET应用程序中使用ZIP文件,该文件具有第三方开源压缩库。这简短的文章通过演示使用System.i.com构造类来解压缩上载的ZIP文件,并在ASP.NET MVC应用程序中创建一个下载。

解压缩上传的zip文件

首先,您需要为您的项目添加对system.io.com的引用。完成此操作中,以下是zip文件的上传表单:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="zip"  /> 
    <div>
        <button class="btn btn-default">Submit</button>
    </div>
}

Note that the form's method is specified as POST and that the enctype attribute is set with a value of multipart/form-data - both prerequisites for being able to upload files. The form is posted to the following controller action:

[HttpPost]
public ActionResult Index(HttpPostedFileBase zip)
{
    var uploads = Server.MapPath("~/uploads");
    using (ZipArchive archive = new ZipArchive(zip.InputStream))
    {
        foreach (ZipArchiveEntry entry in archive.Entries)
        {
            if (!string.IsNullOrEmpty(Path.GetExtension(entry.FullName))) //make sure it's not a folder
            {
                entry.ExtractToFile(Path.Combine(uploads, entry.FullName));
            }
            else
            {
                Directory.CreateDirectory(Path.Combine(uploads, entry.FullName));
            }
        }
    }
    ViewBag.Files = Directory.EnumerateFiles(uploads);
    return View();
}

The action's parameter is an HttpPostedFileBase named after the name attribute of the file upload control in the form. The code creates an instance of the ZipArchive class from the content of the uploaded file and then iterates the contents of the archive. If the name of an entry has a file extension, it is a file. If not, it is a folder. The code will save the extracted file or create a folder accordingly.

为下载创建zip文件

下面的简单示例说明了静态的使用 ZipFile.CreateFromDirectory method which, despite the fact that it is in the System.IO.Compression namespace , actually resides in the System.IO.Compression.FileSystem assembly, so you need to add a reference to that in your controller. The user is presented with a list of checkboxes representing a selection of files to choose from. Submitting the form will result in just those files being packaged up into one zip file and downloaded.

The list of files is passed to the view via ViewBag:

public ActionResult Index()
{
    ViewBag.Files = Directory.EnumerateFiles(Server.MapPath("~/pdfs"));
    return View();
}

文件列在具有一组复选框的表单中:

<h2>Select downloads</h2>
@using(Html.BeginForm("Download", "Home"))
{
    foreach(string file in ViewBag.Files)
    {
        <input type="checkbox" name="files" value="@file" /> @:&nbsp;  
             @Path.GetFileNameWithoutExtension(file) <br />
    }
    <div>
        <button class="btn btn-default">Submit</button>
    </div>
}

The form posts to an action called Download which consists of the following code:

[HttpPost]
public FileResult Download(List<string> files)
{
    var archive = Server.MapPath("~/archive.zip");
    var 临时  = Server.MapPath("~/temp");

    // clear any existing archive
    if (System.IO.File.Exists(archive))
    {
        System.IO.File.Delete(archive);
    }
    // empty the temp folder
    Directory.EnumerateFiles(temp).ToList().ForEach(f => System.IO.File.Delete(f));

    // copy the selected files to the temp folder
    files.ForEach(f => System.IO.File.Copy(f, Path.Combine(temp, Path.GetFileName(f))));

    // create a new archive
    ZipFile.CreateFromDirectory(temp, archive);

    return File(archive, "application/zip", "archive.zip");
}

The user selection is captured in the files parameter. The code checks to see if a file called archive.zip. 存在于以前的操作状态,它确实如此,它被删除了。然后一个文件夹 临时 被清除了任何现有文件。接下来,将所选文件从其源目录复制到 临时 folder. The ZipFile.CreateFromDirectory method generates a zip file from the temp directory contents and saves it as archive.zip.. Finally, it is written to the Response.

简化了这两个示例以说明尽可能清楚地执行任务所需的主要类和方法。处理上载时,您应该添加验证以检查上传的文件实际上是一个zip文件。此外,创建的zip文件被放入硬编码文件夹中。如果您有一个忙碌的网站,其中多个用户同时下载zip文件,则可能希望使用GUID作为文件夹名称,而是避免一个用户下载覆盖另一个用户的可能性。