从 S3 Bucket 下载图像后未在内容配置中获取图像内容

Not getting image content in content-disposition after downloading image from S3 Bucket

我正在使用以下代码从 AWS S3 存储桶下载图像。

com.amazonaws.services.s3.model.S3Object object = s3Client.getObject(new 
GetObjectRequest(bucketName, mediaItem.getFileName()));
    S3ObjectInputStream objectData = object.getObjectContent();
    object.close();
    return objectData.toString();

我收到 200 个响应,但在图像视图中它说不是图像。

这是从 AWS S3 存储桶中获取对象并将对象流写入 servlet 响应的代码。我使用内容配置为 "inline",所以它直接在浏览器上显示对象。它不会弹出 "save as"。您可以根据需要更改为不同的内容配置。

Content disposition

我已经使用访问密钥和密钥获取了 s3 客户端。如果您是 运行 来自 EC2 且有权访问 S3 存储桶的应用程序,则可以将其更改为 InstanceProfileCredentialsProvider(即注释代码)。

public class GetS3Object extends HttpServlet {

    private static final long serialVersionUID = -3924600769478978726L;

    private static Logger logger = Logger.getLogger(GetS3Object.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletOutputStream out = resp.getOutputStream();

        /*AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withCredentials(new InstanceProfileCredentialsProvider(false)).build();*/

        BasicAWSCredentials awsCreds = new BasicAWSCredentials("accesskey", "secretkey");
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                                .build();

        try {

            GetObjectRequest getObjectRequest = new GetObjectRequest("yourbucketName", "objectkey");
            S3Object s3Object = s3Client.getObject(getObjectRequest);

            byte[] s3Content = org.apache.commons.io.IOUtils.toByteArray(s3Object.getObjectContent());

            resp.setHeader("Content-Type",
                    getServletContext().getMimeType(s3Object.getObjectMetadata().getContentType()));
            resp.setHeader("Content-Length", String.valueOf(s3Content.length));
            resp.setHeader("Content-Disposition", "inline; filename=\"" + "Google_logo.jpeg" + "\"");

            out.write(s3Content);

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }

    }

}