Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download multiple files contained in a list of byte array in ASP.NET MVC C#

Tags:

c#

asp.net-mvc

I'm developing an ASP.NET MVC 5 application, and I wrote a code that allows me to download files stored in a SQL Server database as varbinary, I'm able to download a single file with this:

public JsonResult PrepareSingleFile(int [] IdArray)
{
    ImageContext _contexte = new ImageContext();
    var response =_contexte.contents.Find(IdArray.FirstOrDefault());
    //byte[] FileData = 
    Encoding.UTF8.GetBytes(response.image.ToString());
    byte[] FileData = response.image;
    Session["data"] = FileData;
    Session["filename"] = response.FileName;

    return Json(response.FileName);
}

public FileResult DownloadSingleFile()
{
    var fname = Session["filename"];
    var data = (byte[]) Session["data"];
    //return File(data,"application/pdf");
    return File(data,System.Net.Mime.MediaTypeNames.Application.Pdf, fname.ToString()+".pdf");
}

But now I want to download multiple files, so I'm getting the data of each file as a byte array and putting those byte arrays inside a List<byte[]> and I want to download those files as a zip file, so how can I do that?

I tried this:

File(data,"the Mime Type", "file name.extension")

But it doesn't work when data is a List<byte[]>.

like image 325
Haytham Avatar asked Apr 22 '18 21:04

Haytham


1 Answers

You can do that using ZipArchive class available in .NET framework 4.5. You may add a method in your controller that accepts a List<byte[]> parameter and then converts each byte[] to a memory stream and puts it in a zip file like this one,

 public FileResult DownloadMultipleFiles(List<byte[]> byteArrayList)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
            {
                foreach(var file in byteArrayList)
                {
                    var entry = archive.CreateEntry(file.fileName +".pdf", CompressionLevel.Fastest);
                    using (var zipStream = entry.Open()) 
                    {
                        zipStream.Write(file, 0, file.Length);
                    }
                }
            }

            return File(ms.ToArray(), "application/zip", "Archive.zip");
        }
    }
like image 167
Nelson Jr. Avatar answered Nov 12 '22 21:11

Nelson Jr.