我的 AWS S3
包含一些文件,我想通过我的应用程序将这些文件下载为 zip 文件。我能够成功下载 zip 文件,但在下载文件时出现错误意外的存档结束
,并且 zip 内的 CSV 文件大小为 0。
我确实进行了很多挖掘,但无法理解确切的解决方案。
代码如下:
String zipFileName = "MyZipFile.zip";
String fileName = "test.csv";
filePath = new String(Base64.getDecoder().decode(filePath));
System.out.println("file:" + filePath);
// get file from S3
S3Object s3Obj = awsClient.downloadFile(filePath);
byte[] s3Bytes = s3Obj.getObjectContent().readAllBytes();
// create zip
ByteArrayOutputStream byteArrOutputStream = new ByteArrayOutputStream(s3Bytes.length);
ZipOutputStream zipOutStream = new ZipOutputStream(byteArrOutputStream);
ZipEntry zip = new ZipEntry(fileName);
zipOutStream.putNextEntry(zip);
zipOutStream.write(s3Bytes, 0, s3Bytes.length);
byte[] streamBytes = byteArrOutputStream.toByteArray();
// close streams
zipOutStream.closeEntry();
zipOutStream.close();
closeQuietly(byteArrOutputStream);
// prepare download
System.out.println("streamBytes:" + streamBytes + " len:" + streamBytes.length);
System.out.println("s3Bytes:" + s3Bytes + " len:" + s3Bytes.length);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentLength(streamBytes.length);
headers.setContentDispositionFormData("attachment", zipFileName);
最佳答案
我认为您应该关闭 zip 输出流,以便在提取字节数组之前将所有内容写入底层字节数组流...即将行重新排序为:
// close streams
zipOutStream.closeEntry();
zipOutStream.close();
byte[] streamBytes = byteArrOutputStream.toByteArray();
closeQuietly(byteArrOutputStream);
关于java - 无法打开使用 spring-boot 下载的 S3 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57409645/