gpt4 book ai didi

amazon-s3 - S3 下载 pdf - REST API

转载 作者:行者123 更新时间:2023-12-03 08:01:46 27 4
gpt4 key购买 nike

我正在尝试使用 Spring Boot Rest API 为我存储在 S3 上的 PDF 之一提供服务。

以下是我的代码:

        byte[] targetArray = null;

InputStream is = null;

S3Object object = s3Client
.getObject(new GetObjectRequest("S3_BUCKET_NAME", "prefixUrl"));

InputStream objectData = object.getObjectContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(objectData));

char[] charArray = new char[8 * 1024];
StringBuilder builder = new StringBuilder();
int numCharsRead;
while ((numCharsRead = reader.read(charArray, 0, charArray.length)) != -1) {

builder.append(charArray, 0, numCharsRead);
}
reader.close();

objectData.close();
object.close();
targetArray = builder.toString().getBytes();

is = new ByteArrayInputStream(targetArray);


return ResponseEntity.ok().contentLength(targetArray.length).contentType(MediaType.APPLICATION_PDF)
.cacheControl(CacheControl.noCache()).header("Content-Disposition", "attachment; filename=" + "testing.pdf")
.body(new InputStreamResource(is));

当我使用 postman 访问我的 API 时,我可以下载 PDF 文件,但问题是它完全是空白的。可能是什么问题?

S3 流式传输数据并且不保留缓冲区,并且数据是二进制( PDF ),因此如何将此类数据提供给使用 Rest API。

如何解决这个问题?

最佳答案

遵循简单的代码应该对您有用,不确定您为什么要尝试将字符转换为字节,反之亦然?
试试这个,效果很好。 postman /浏览器。

@GET
@RequestMapping("/document")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces("application/pdf")
public ResponseEntity<InputStreamResource> getDocument() throws IOException {

final AmazonS3 s3 = AmazonS3ClientBuilder.defaultClient();

S3Object object = s3.getObject("BUCKET-NAME", "DOCUMENT-URL");
S3ObjectInputStream s3is = object.getObjectContent();

return ResponseEntity.ok()
.contentType(org.springframework.http.MediaType.APPLICATION_PDF)
.cacheControl(CacheControl.noCache())
.header("Content-Disposition", "attachment; filename=" + "testing.pdf")
.body(new InputStreamResource(s3is));
}

关于amazon-s3 - S3 下载 pdf - REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50043662/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com