package froala.editor.utils.view; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.servlet.view.AbstractView; import egovframework.com.cmm.util.EgovResourceCloseHelper; @Component public class ImageView extends AbstractView{ private static final Logger LOGGER = LoggerFactory.getLogger(ImageView.class); @Override protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws IOException { String path = (String) model.get("path"); Path source = Paths.get(path); // 응답의 타입이 이미지임을 알려줍니다. response.setContentType(Files.probeContentType(source)); // 한글 파일명일 경우를 위해 파일명 인코딩 String filename = (String) model.get("origin_file_nm"); if (StringUtils.isBlank(filename)) { filename = source.getFileName().toString(); } // String filename = source.getFileName().toString(); String userAgent = request.getHeader("User-Agent"); String conVstr = null; if (userAgent.contains("MSIE")) { conVstr = URLEncoder.encode(filename,"UTF-8"); } else if (userAgent.contains("Trident")) { conVstr = URLEncoder.encode(filename,"UTF-8"); } else if(userAgent.contains("Chrome")) { conVstr = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); } else if(userAgent.contains("Opera")) { conVstr = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); } else if (userAgent.contains("Mozilla")){ conVstr = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); } else { conVstr = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); } // 웹브라우저 상에서 이미지 저장시 파일명을 지정합니다. response.setHeader("Content-Disposition", "attachment; filename=" + conVstr + ";"); // 파일로부터 byte를 읽음 byte[] bytes = readFile(path); if (bytes != null) { write(response, bytes); } } /** * 파일로부터 byte 배열 읽어오기 */ private byte[] readFile(String path) throws IOException { BufferedInputStream bis = null; byte[] bytes = null; FileInputStream fis = null; try { File file = new File(path); if (Boolean.FALSE.equals(file.exists())) { return null; } fis = new FileInputStream(path); bis = new BufferedInputStream(fis); int length = bis.available(); bytes = new byte[length]; bis.read(bytes); } catch(IOException e){ LOGGER.error("fail to process imageView readFile {}", e); } finally { EgovResourceCloseHelper.close(fis, bis); } return bytes; } /** * 응답 OutputStream에 파일 내용 쓰기 */ private void write(HttpServletResponse response, byte[] bytes) throws IOException { OutputStream output = response.getOutputStream(); output.write(bytes); output.flush(); } }