【发布时间】:2020-10-02 19:39:49
【问题描述】:
我正在尝试使用 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();
}
在调试时,我发现图像输入流的“内容长度”为-1。 这里有什么问题? 有没有更好的方法将图片从 URL 上传到 S3 Bucket?
【问题讨论】: