1

I'm working on .net core web API and wanting to get the files from s3 and zip before download.
Can you point me to the right direction? I searched the web and couldn't find a solution.

so this block of code is able to read from s3 files (the bucket may contain different types of files), I just dont know how to zip all of them before download

public async Task GetFilesAsync(string projectId)        {
        string bucketName = "MyBucket";
        ListObjectsRequest request = new ListObjectsRequest
        {
            BucketName = bucketName
        };

        ListObjectsResponse response = await _client.ListObjectsAsync(request);
        var item = response.S3Objects;

        foreach (var objt in item)
        {
            GetObjectRequest request1 = new GetObjectRequest();
            request1.BucketName = bucketName;
            request1.Key = objt.Key;

            GetObjectResponse Response = await _client.GetObjectAsync(request1);

           //HOW TO ZIP all of the files here and download as single file
            using (Stream responseStream = Response.ResponseStream)
            {
               // Response.WriteResponseStreamToFile("downloadLocation" + "\\" + objt.Key);
            }

        }
}

I'm trying this solution but cannot make it work:

using (var compressedFileStream = new MemoryStream())
{
    //Create an archive and store the stream in memory.
    using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
    {
        foreach (var caseAttachmentModel in item)
        {
            //Create a zip entry for each attachment
            var zipEntry = zipArchive.CreateEntry(caseAttachmentModel.Key);

            //Get the stream of the attachment
            using (var originalFileStream = new MemoryStream(caseAttachmentModel.Body))
            using (var zipEntryStream = zipEntry.Open())
            {
                //Copy the attachment stream to the zip entry stream
                originalFileStream.CopyTo(zipEntryStream);
            }
        }

        return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
    }
}
samantha07
  • 507
  • 1
  • 7
  • 21

0 Answers0