如何避免压缩上传PDF至S3时在项目目录生成多余PDF文件?
解决方案:避免压缩上传S3时生成本地多余PDF文件
问题根源在于代码里的FileUtils.copyToFile(fileInputStream, pdfFile)这行——它把从classloader读取的PDF流直接写到了本地项目目录里,这是完全多余的操作。我们根本不需要把PDF落地到本地,直接将输入流的数据写入ZipOutputStream就能完成压缩,之后上传S3即可。
修改后的代码
public void zipAndUploadToS3() throws IOException { // Create a ByteArrayOutputStream to hold the zip data ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); for (int i = 1; i <= 3; i++) { String pdfFileName = i + ".pdf"; // Create a new entry in the zip file for the PDF ZipEntry entry = new ZipEntry(pdfFileName); zipOutputStream.putNextEntry(entry); InputStream fileInputStream = PdfService.class.getClassLoader().getResourceAsStream(pdfFileName); if (fileInputStream == null) { System.out.println(pdfFileName + " not found"); zipOutputStream.closeEntry(); continue; } byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) > 0) { zipOutputStream.write(buffer, 0, len); } zipOutputStream.closeEntry(); fileInputStream.close(); } zipOutputStream.close(); // Upload the zip file to S3 byte[] zipData = outputStream.toByteArray(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("application/zip"); PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, "my-zip-file.zip", new ByteArrayInputStream(zipData), metadata); s3client.putObject(putObjectRequest); s3client.setObjectAcl(bucketName, "my-zip-file.zip", CannedAccessControlList.PublicRead); String objectUrl = s3client.getUrl(bucketName, "my-zip-file.zip").toString(); System.out.println(objectUrl); }
关键改动说明
- 移除了
FileUtils.copyToFile相关代码,彻底跳过本地PDF文件的生成步骤 - 不再实例化本地
File对象,直接用文件名字符串创建ZipEntry - 处理输入流为空的情况时,新增了关闭当前ZipEntry的操作,避免压缩流程出错
修改后整个压缩过程完全在内存中完成,不会在项目目录生成任何多余文件。
内容的提问来源于stack exchange,提问作者Saurabh Saxena
相关产品推荐
相关产品推荐

