S3 下载 pdf - REST API

S3 download pdf - REST API

我正在尝试使用 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));

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

S3 流式传输数据并且不保留缓冲区并且数据为二进制 (PDF) 那么如何使用 Rest 将此类数据服务器化 API.

如何解决这个问题?

以下简单代码应该适合您,但不确定为什么要尝试将字符转换为字节,反之亦然? 试试这个,效果很好。 PostMan/Browser.

@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));
}