java - 将文本pdf直接保存到s3而无需在本地保存
问题描述
我正在使用 itext 5 和 Java 生成 pdf 文件,并将它们保存在本地,然后将这些本地保存的文件保存在 AWS S3 上。有没有办法直接将它们发送到 S3 而不必在本地保存它们。我看过一些例子,但没有一个对我有用。
这就是生成pdf文件的方式
String path = //local directory on my computer
Document document = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(path));
document.open();
// add text to document
document.close();
这就是我在s3上保存它的方式
public void saveFileToS3(String pathLocal, String pathAws) {
// init aws
PutObjectRequest objectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(folderName + "/" + pathAws)
.build();
CompletableFuture<PutObjectResponse> future = s3Client.putObject(objectRequest,
AsyncRequestBody.fromFile(Paths.get(pathLocal))
);
future.whenComplete((resp, err) -> {
try {
if (resp != null) {
System.out.println("Object uploaded. Details: " + resp);
} else {
err.printStackTrace();
}
} finally {
s3Client.close();
}
});
future.join();
}
String pathLocal是我在本地保存文件的路径,而String pathAws是 S3 上保存文件的路径。
解决方案
所以我找到了一种方法,我将itext文件转换为字节数组并将pdf文件作为字节数组上传
Document document = new Document();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfWriter.getInstance(document, byteArrayOutputStream);
document.open();
//add stuff to pdf
document.close();
//convert it into a byte array
byte[] pdfBytes = byteArrayOutputStream.toByteArray()
将其上传到 S3 时,我传递了字节而不是文件路径,就像我之前所做的那样
CompletableFuture<PutObjectResponse> future = s3Client.putObject(objectRequest,
AsyncRequestBody.fromBytes(pdfBytes)
);
推荐阅读
- python - Sklearn 错误,无法从“joblib”导入名称“Logger”
- python-3.x - 将 Pandas 列操作为不同的标签
- algorithm - 获取给定数字数组的所有唯一目标总和组合
- c# - 如何将不同类型的参数传递给通用 ServiceFilter 或 ActionFilter
- python-3.x - Python 数组交集
- javascript - 如何在jquery中的内部html下动态加载路径
- docker - 如何在开发模式下将 jira 作为 docker 容器运行?
- node.js - Mongoose:自定义验证器的 isAsync 选项已弃用
- python - Python:尝试合并两个必须相加值的字典时出现问题
- reactjs - 在 react Typescript 中通过地图显示数组数据