无法打开使用spring-boot下载的S3 zip文件

时间:2019-08-08 09:42:29

标签: java spring-boot amazon-s3

我的AWS S3包含一些文件,我想通过我的应用程序将这些文件下载为zip文件。我能够成功下载zip文件,但是当文件出现错误Unexpected end of archive时,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);

1 个答案:

答案 0 :(得分:1)

我认为您应该关闭zip输出流,以将所有内容写入底层字节数组流 ,然后再提取字节数组...即将行重新排序为:

// close streams
zipOutStream.closeEntry();
zipOutStream.close();
byte[] streamBytes = byteArrOutputStream.toByteArray();
closeQuietly(byteArrOutputStream);