0

I want to download multiple files with different keys as a batch (.zip) e.g, I have keys file1 (abc.txt), file2 (xyz.pdf) and file3 (qwe.png) and I want to download abc.txt and qwe.png using their respective key but all together in a form zip.

I am trying to do it using MVC5 controller C#.

This is for one file. I want for multiple files in a single go.

using (client = new AmazonS3Client(AWSCredentials, RegionEndPoint)) {
GetObjectRequest request = new GetObjectRequest {
    BucketName = existingBucketName,
    Key = newFileName
};
using (GetObjectResponse response =        client.GetObject(request)) {
    byte[] buffer = ReadFully(response.ResponseStream);
    Response.OutputStream.Write(buffer, 0, buffer.Length);
    Response.AddHeader("content-disposition", "attachment; filename=" + newFileName);
    }
}

.zip file is the preferred output

Mikev
  • 2,012
  • 1
  • 15
  • 27

1 Answers1

0

It's easy, you create a method that convert a list of files into a zip file.

public byte[] GetZippedFileFromFileList(List<KeyValuePair<string, byte[]>> fileList)
{
    using (MemoryStream zipStream = new MemoryStream())
    {
        using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
        {
            foreach (var file in fileList)
            {
                var zipEntry = zip.CreateEntry(file.Key);
                using (var writer = new StreamWriter(zipEntry.Open()))
                {
                    new MemoryStream(file.Value).WriteTo(writer.BaseStream);
                }
            }
        }

        return zipStream.ToArray();
    }
}

In my parameter fileList, string is the file name, and byte[] is the file. Then in your controller you do something like this :

public ActionResult returnZipFile()
{
    return this.File(this.GetZippedFileFromFileList(fileList), "application/zip", "myZippedFile.zip"));
}
Tortillas
  • 78
  • 9