微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 Java 中的 AWS S3 图像获取内容类型

如何解决从 Java 中的 AWS S3 图像获取内容类型

我有一个图像存储在 AWS S3 存储桶中

URL url = new URL(urlString);
        URI dataUri = null;
        if (null != url) {
            try (InputStream inStreamGuess = url.openStream();
                    InputStream inStreamConvert = url.openStream();
                    ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                String contentType = URLConnection.guessContentTypeFromStream(inStreamGuess);
                if (null != contentType) {
...
}

内容类型为空

解决方法

要使用 Java 获取 Amazon S3 存储桶中对象的内容类型,请使用适用于 Java V2 的 AWS 开发工具包。

https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html#headObject-

使用返回 HeadObjectResponse 对象的 headObject 方法。然后调用: https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/model/HeadObjectResponse.html#contentType-- 方法。

有效的 Java V2 示例

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;

/**
 * To run this AWS code example,ensure that you have setup your development environment,including your AWS credentials.
 *
 * For information,see this documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class GetObjectContentType {

    public static void main(String[] args) {

        final String USAGE = "\n" +
                "Usage:\n" +
                "    GetObjectContentType <bucketName> <keyName>>\n\n" +
                "Where:\n" +
                "    bucketName - the Amazon S3 bucket name. \n\n"+
                "    keyName - the key name. \n\n";

        if (args.length != 2) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String bucketName = args[0];
        String keyName = args[1];

        Region region = Region.US_WEST_2;
        S3Client s3 = S3Client.builder()
                .region(region)
                .build();

        getContentType(s3,bucketName,keyName);
        s3.close();
    }

    
    public static void getContentType (S3Client s3,String bucketName,String keyName) {

        try {
            HeadObjectRequest objectRequest = HeadObjectRequest.builder()
                    .key(keyName)
                    .bucket(bucketName)
                    .build();

            HeadObjectResponse objectHead = s3.headObject(objectRequest);
            String type = objectHead.contentType();
            System.out.println("The object content type is "+type);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。