首页 > 解决方案 > Powershell - gzip 大文件并使用流加载到 s3

问题描述

我正在尝试使用 gzip 压缩一些 csv 文件,然后将它们上传到 S3。我需要使用流来压缩和加载,因为文件可能非常大,我不想在将文件加载到 s3 之前将其写回磁盘。我是在 Powershell 中使用流的新手,我正在努力解决这个问题。

这是我到目前为止所拥有的,但我无法让它发挥作用。它加载了一个非常小的 gzip 文件,其中显示了我的原始文件,但我无法提取它 - 我收到“数据意外结束”错误。我相信它没有最终确定 gzip 流或类似的东西。如果我删除“gzip”命令并将 inputFileStream 写入 S3,那么它可以加载未压缩的文件,所以我知道使用流的 S3 加载是有效的。
另外,我正在使用“CopyTo”,我相信它会将整个文件放入我不想要的内存中(如果我的想法不正确,请告诉我)。

$sourcePath =  "c:\temp\myfile.csv"
$bucketName = "mybucket"
$s3Key = "staging/compress_test/"

$fileInfo = Get-Item -Path $sourcePath
$destPath = "$s3Key$($fileInfo.Name).gz"

$outputMemoryStream = New-Object System.IO.MemoryStream 
$gzipStream = New-Object System.IO.Compression.GZipStream $outputMemoryStream, ([IO.Compression.CompressionMode]::Compress)

$inputFileStream = New-Object System.IO.FileStream $sourcePath, ([IO.FileMode]::Open), ([IO.FileAccess]::Read), ([IO.FileShare]::Read)
$inputFileStream.CopyTo($gzipStream)

Write-S3Object -BucketName $destBucket -Key $destPath -Stream $outputMemoryStream -ProfileName Dev -Region us-east-1

$inputFileStream.Close()
$outputMemoryStream.Close()

更新:感谢@FoxDeploy。我现在至少可以加载文件了。在写入 S3 导致 gzip 完成之前,我需要关闭 gzip 流。但正如我怀疑的那样,“CopyTo”会导致整个文件被压缩并存储在内存中,然后加载到 S3。如果可能的话,我希望它流式传输到 S3,因为它正在压缩以减少内存负载。
这是当前的工作代码:

$sourcePath =  "c:\temp\myfile.csv"
$bucketName = "mybucket"
$s3Key = "staging/compress_test/"

$fileInfo = Get-Item -Path $sourcePath
$destPath = "$s3Key$($fileInfo.Name).gz"

$outputMemoryStream = New-Object System.IO.MemoryStream 
$gzipStream = New-Object System.IO.Compression.GZipStream $outputMemoryStream, ([IO.Compression.CompressionMode]::Compress), true

$inputFileStream = New-Object System.IO.FileStream $sourcePath, ([IO.FileMode]::Open), ([IO.FileAccess]::Read), ([IO.FileShare]::Read)
$inputFileStream.CopyTo($gzipStream)

$gzipStream.Close()

Write-S3Object -BucketName $bucketName -Key $destPath -Stream $outputMemoryStream -ProfileName Dev -Region us-east-1

$inputFileStream.Close()
$outputMemoryStream.Close()

标签: amazon-web-servicespowershellamazon-s3filestreamgzipstream

解决方案


推荐阅读