使用HttpResponse将byte []作为file.jpg添加到ZipFile

时间:2016-10-10 11:56:00

标签: c# asp.net httpresponse

我已成功下载此代码:

byte[] bytes;
bytes = Convert.FromBase64String(lehrling.passfoto);
Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "image/jpg";
Response.AddHeader("content-disposition", "attachment; filename=" + lehrling.vorname + "." + lehrling.nachname + ".jpeg");
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.End()

这很好用。我从中获得了一个jpeg文件。现在:

我创建了一个for循环,为每个bytearray执行上面显示的代码:

    for (int i = 0; i < anzahlBilder; i++)
    {
         //My Code here
    }
    Response.End()

我从其他地方获得anzahlBilder。这对我的问题不重要。我将Response.End()放在for-loop之外,否则它会在1 image下载后结束。

要压缩:

现在我要创建一个.Zip文件,其中包含我的所有图像。我不知道该怎么做。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

使用System.IO.Compression.ZipFile

您需要为程序集添加一个dll引用,“System.IO.Compression.FileSystem.dll”并导入名称空间。

System.IO.Compression

在顶部。

    ZipFile zipFile = new ZipFile();
    for(int i = 0; i < anzahlBilder; i++)
    {
        using (MemoryStream ms= new MemoryStream(Convert.FromBase64String(lehrling.passfoto)))
        {
            Image userImage = Image.FromStream(ms);   
            userImage.Save(ms, ImageFormat.Jpeg);  
            ms.Seek(0, SeekOrigin.Begin);
            byte[] imageData = new byte[ms.Length];
            ms.Read(imageData, 0, imageData.Length);
            zipFile.AddEntry(lehrling.vorname + "." + lehrling.nachname + ".jpeg", imageData);
        }
    }

    zipFile.Save(Response.OutputStream);

代替lehrling.passfotolehrling.vorname + "." + lehrling.nachname + ".jpeg"进行必要的更改以使其发挥作用。