一次下载zip格式的多个文件

时间:2018-04-09 11:20:13

标签: c# asp.net-mvc downloadfile multifile

我想创建一个循环来遍历我的数据库中具有特定ID的所有文件,并以zip格式下载它们。每个文件都有一个名称。我想通过名称+ timenow将它保存在单个zipfile中。

//this code is working fine for single file
if (fileattach != null && fileattach.ContentLength > 0)
    fileattach.FileDownloadName = attach.name + System.DateTime.Now + ".jpg";
return fileattach; 

我试着按照以下方式做,但我真的没有那个

的逻辑
public ActionResult downloadF(int? id) {
    var attach      = db.details.First(a => a.id == id);
    var fileattach  = new FileContentResult(attach.foto.ToArray(), "application/octet-stream");
    var fileattach2 = new FileContentResult(attach.passport.ToArray(), "application/octet-stream");
    var fileattach3 = new FileContentResult(attach.degree.ToArray(), "application/octet-stream");

    using (var memoryStream = new MemoryStream()) {
        using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) {
            for (int i = 0; i < 3; i++) {

                //how to define files object as we do in the upload by defining 
                //HttpPostedFileBase here it is not working
                HttpPostedFileBase Files.ElementAt(i) != null 
                ziparchive.CreateEntryFromFile(filesCol[i].name);
            }
        }

        return File(memoryStream.ToArray(), "application/zip", "Attachments.zip");
    }

1 个答案:

答案 0 :(得分:-1)

关于如何创建zip文件,请参阅Creating a ZIP Archive in Memory Using System.IO.Compression,您将找到一个使用文件的答案,并向下滚动以了解如何使用memorystream

所以你的代码看起来很像,不是最优的,你可以为每种类型的文档创建一个辅助函数

public ActionResult downloadF(int? id)
{
    var attach = db.details.First(a => a.id == id);

    using (var memoryStream = new MemoryStream())
    {
        using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            AddToArchive(ziparchive, "foto.png", attach.foto.ToArray());
            AddToArchive(ziparchive, "passport.png", attach.passport.ToArray());
            AddToArchive(ziparchive, "degree.png", attach.degree.ToArray());
        }
        return File(memoryStream.ToArray(), "application/zip", "Attachments.zip");
    }
}

private void AddToArchive(ZipArchive ziparchive, string fileName, byte[] attach)
{
    var zipEntry = ziparchive.CreateEntry(fileName, CompressionLevel.Optimal);
    using (var zipStream = zipEntry.Open())
    using (var streamIn = new MemoryStream(attach))
    {
        streamIn.CopyTo(zipStream);
    }
}