diff options
Diffstat (limited to 'juick-server-web/src/main/java/com/juick/server/util')
-rw-r--r-- | juick-server-web/src/main/java/com/juick/server/util/HttpUtils.java | 43 |
1 files changed, 13 insertions, 30 deletions
diff --git a/juick-server-web/src/main/java/com/juick/server/util/HttpUtils.java b/juick-server-web/src/main/java/com/juick/server/util/HttpUtils.java index db920e88..35f594f3 100644 --- a/juick-server-web/src/main/java/com/juick/server/util/HttpUtils.java +++ b/juick-server-web/src/main/java/com/juick/server/util/HttpUtils.java @@ -17,13 +17,11 @@ package com.juick.server.util; import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -62,14 +60,15 @@ public class HttpUtils { return StringUtils.EMPTY; } public static String downloadImage(URL url, String tmpDir) throws Exception { - String attachmentFName = null; - Exception ex = null; - - InputStream is = null; - FileOutputStream fos = null; + URLConnection urlConn; try { - URLConnection urlConn = url.openConnection(); - is = urlConn.getInputStream(); + urlConn = url.openConnection(); + } catch (IOException e) { + logger.error(String.format("Failed open url: %s", url.toString())); + throw e; + } + + try (InputStream is = urlConn.getInputStream()) { String mime = urlConn.getContentType(); String attachmentType; @@ -85,28 +84,12 @@ public class HttpUtils { throw new Exception("Wrong file type: " + mime); } - attachmentFName = DigestUtils.md5Hex(UUID.randomUUID().toString()) + "." + attachmentType; - fos = new FileOutputStream(Paths.get(tmpDir, attachmentFName).toString()); - IOUtils.copy(is, fos); - } catch (Exception e) { - ex = e; - attachmentFName = null; - } finally { - try { - if (is != null) { - is.close(); - } - } finally { - if (fos != null) { - fos.close(); - } - } - } - - if (ex != null) { - throw ex; - } else { + String attachmentFName = DigestUtils.md5Hex(UUID.randomUUID().toString()) + "." + attachmentType; + Files.copy(is, Paths.get(tmpDir, attachmentFName)); return attachmentFName; + } catch (Exception e) { + logger.error(String.format("Failed download image by url: %s", url.toString()), e); + throw e; } } } |