繁体   English   中英

使用 Java SDK 将图像从 url 上传到 Amazon S3

[英]Upload image from url to Amazon S3 using Java SDK

我正在尝试使用 java sdk 将图像从 postimage.org 上传到 Amazon S3 存储桶。 我可以看到在我希望创建它的文件夹位置的 s3 存储桶中创建了一个文件。 但是,图像文件与 postimage.org 中的原始图像不同。 事实上,它只是一个 11.5 kb 的“空”图像文件。

[参考下面我的代码]

我的代码:

    @Test
    void uploadToS3() throws IOException {
        AWSCredentials credentials = new BasicAWSCredentials(KEY, SECRET);
        AmazonS3 amazonS3= AmazonS3ClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(REGION)
                .build();
        URL imageURL=new URL("https://i.postimg.cc/NMp9ZvMD/4X1.jpg");
        InputStream is = getImageInputStream(imageURL);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("image/jpeg");
        amazonS3.putObject(new PutObjectRequest(MY_BUCKET, "my/folder/path/4X1.jpg",is,metadata));
        is.close();

    }

    // THIS IS A COPIED CODE FROM ANOTHER STACKOVERFLOW QUESTION
    private InputStream getImageInputStream(URL url) throws IOException {


        // This user agent is for if the server wants real humans to visit
        String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";

        // This socket type will allow to set user_agent
        URLConnection con = url.openConnection();

        // Setting the user agent
        con.setRequestProperty("User-Agent", USER_AGENT);

        //Getting content Length
        int contentLength = con.getContentLength();
        System.out.println("\n\n\n\n\n *****************File contentLength = " + contentLength + " bytes ****************\n\n\n\n");


        // Requesting input data from server
        return con.getInputStream();

    }

调试时发现图片输入stream的“内容长度”为-1。 这里有什么问题? 有没有更好的方法将图像从 URL 上传到 S3 存储桶?

这里有两点错误,首先你应该使用 HEAD 调用获取文件的 contentLength,如下所示:

public static Long getContentLength(String urlStr) {
    Long contentLength = null;
    HttpURLConnection conn = null;
    try {
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36");
        conn.setRequestMethod("HEAD");
        contentLength = conn.getContentLengthLong();
        LOG.info("Content length {}", contentLength);
    } catch (Exception e) {
        LOG.info("Error getting content length: {}", e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return contentLength;
}

其次,上传时必须在 S3 元数据上设置 content-length header

....
           metadata.setContentLength(getContentLength(fileUrl));
....
 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM