如何从s3获取文件并在下载之前将其压缩

时间:2019-07-03 17:10:46

标签: .net amazon-s3 aws-sdk asp.net-core-webapi

我正在使用.net核心Web API,并希望在下载之前从s3和zip获取文件。
你能指出我正确的方向吗?我在网上搜索,找不到解决方案。

因此该代码块能够读取s3文件(存储桶中可能包含不同类型的文件),我只是不知道如何在下载之前压缩所有文件

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);
            }

        }
}

我正在尝试此解决方案,但无法使其起作用:

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" };
    }
}

0 个答案:

没有答案