I think this code looks ugly, especially with the multiple try-catch blocks, but I don't know how to rewrite it:
public String handleFileUpload(@RequestParam String url,@RequestParam String fileName, RedirectAttributes redirectAttributes, HttpServletResponse response) {
InputStream inputStream;
try {
inputStream = new URL(url).openStream();
} catch (IOException e) {
LOG.error("Cannot open stream by url=[{}]", url);
try {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Cannot open stream by url=" + url);
} catch (IOException e1) {
LOG.error("Cannot send error");
}
return null;
}
try {
File file = File.createTempFile("tmp", ".txt", new File(System.getProperty("user.dir")));
byte[] binary = IOUtils.toByteArray(inputStream);
FileUtils.writeByteArrayToFile(file, binary);
UploadedMultipartFile multipartFile = new UploadedMultipartFile(file, file.length(), "jpg",
"formParameter", fileName);
MultipartFileWrapper multipartFileWrapper = new MultipartFileWrapper();
multipartFileWrapper.setMultipartFile(multipartFile);
redirectAttributes.addFlashAttribute(multipartFileWrapper);
} catch (IOException e) {
LOG.error("Cannot save file [{}] from [{}]",fileName, url);
try {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Cannot save file " + fileName);
} catch (IOException e1) {
LOG.error("Cannot send error");
}
return null;
}
return "redirect:/member/uploadImage";
}