S3 下载 pdf - REST API [英] S3 download pdf - REST API

查看:30
本文介绍了S3 下载 pdf - REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to serve one of my PDF stored on S3 using Spring Boot Rest API.

以下是我的代码:

        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 文件,但问题是它完全是空白的.可能是什么问题?

When I hit my API using postman, I am able to download PDF file but the problem is it is totally blank. What might be the issue ?

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

S3 streams the data and does not keep buffer and the data is in binary ( PDF ) so how to server such data to using Rest API.

如何解决这个问题?

推荐答案

以下简单的代码应该对您有用,但不确定您为什么要尝试将字符转换为字节,反之亦然?试试这个,效果很好.邮递员/浏览器.

Following simple code should work for you, not sure why are you trying to convert characters to bytes and vice-versa? Try this one, it works fine. Both 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));
}

这篇关于S3 下载 pdf - REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆