有人正在提供一个s3预签名的网址,以便我可以上传我的图片到该链接。我所有的照片都在网站上。java中有没有一种方法可以将图像url复制到提供的新url中?
我正试着这么做。似乎有点过分了
try {
// Get Image from URL
URL urlGet = new URL("http://something.com/something.png");
BufferedImage image = ImageIO.read(urlGet);
//for png
ImageIO.write(image, "png",new File("/something.png"));
// for jpg
//ImageIO.write(image, "jpg",new File("/something.jpg"));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", outputStream);
outputStream.flush();
byte[] imageInBytes = outputStream.toByteArray();
outputStream.close();
URL url = new URL(putUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod(HttpMethod.PUT);
connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, PNG_MIME_TYPE);
OutputStream stream = connection.getOutputStream();
try {
stream.write(imageInBytes);
} finally {
stream.close();
connection.disconnect();
}
switch (connection.getResponseCode()) {
case HttpURLConnection.HTTP_OK:
return "";
default:
break;
}
} catch (Exception e) {
log.error("Exception occured", e);
throw e;
}
1条答案
按热度按时间vq8itlhq1#
当您可以保留原始文件的字节流时,转换为BuffereImage并返回副本就没有意义了。第一部分可以替换为从网站中提取字节的简单调用:
哪里
read()
是:如果您使用jdk11以后的版本,您可以尝试使用httpclient类进行get和posts,例如,如果传递它,则执行与上面相同的操作
urlGet.toURI()
: