Controller.java

//Controller
//첨부파일 image 보여주는 api
	@RequestMapping(value="/api/img/print/{idx}" , method = {RequestMethod.GET})
	public ModelAndView   getPublicImage(@PathVariable("idx") String idx, HttpServletRequest req, HttpServletResponse res) {
		
		FileInputStream fis = null;
		
		File file = fileService.getFileObject(idx);
		
		ModelAndView mav = new ModelAndView();
		try {				
				mav.setView(new AttachDownloadView());
				mav.addObject("file", file);
			    mav.addObject("filename", "filename");
			    res.setContentType( "image/gif" );		
			} 
		
		catch (Exception e) {
				e.getStackTrace();
			}		 		
			    return mav;
		}	

 

AttachDownloadView.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.travel.util.RequestUtil;
import com.travel.util.ResponseUtil;
import com.travel.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.CacheControl;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

public class AttachDownloadView extends AbstractView {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public AttachDownloadView() {
        setContentType("applicaiton/download;charset=utf-8");
    }

    private void setDownloadFileName(String fileName, HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException {

        fileName = StringUtils.encodeFileNm(fileName, RequestUtil.getBrowser(request));
        String headerValue = CacheControl.maxAge(365, TimeUnit.DAYS).getHeaderValue();

        response.setHeader("Cache-Control", headerValue);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
        response.setHeader("Content-Transfer-Encoding", "binary");
    }

    private void downloadFile(File downloadFile, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        OutputStream out = response.getOutputStream();
        FileInputStream in = new FileInputStream(downloadFile);

        try {
            FileCopyUtils.copy(in, out);
            out.flush();
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (IOException ioe) {
                logger.warn(ioe.getMessage(), ioe);
            }
            try {
                if (out != null)
                    out.close();
            } catch (IOException ioe) {
                logger.warn(ioe.getMessage(), ioe);
            }
        }
    }

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
        try {
            this.setResponseContentType(request, response);

            File downloadFile = (File) model.get("file");
            String filename = (String) model.get("filename");

            if (logger.isDebugEnabled()) {
                logger.debug("downloadFile {} {}", filename, downloadFile);
            }
            if (downloadFile.exists() == false) {
                ResponseUtil.alertAndBack(response, "파일이 없습니다.");
                return;
            }

            this.setDownloadFileName(filename, request, response);

            response.setContentLength((int) downloadFile.length());
            this.downloadFile(downloadFile, request, response);
        } catch (Exception e) {
            throw e;
        }
    }
}

 

RequestUtil.java

import java.net.URI;
import java.util.Enumeration;
import java.util.Map;
import java.util.NoSuchElementException;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.util.UriComponentsBuilder;
import com.google.common.collect.Maps;

public class RequestUtil {

  public static String getCookieValue(HttpServletRequest request, String cookieName) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookieName != null) {
      for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
          return cookie.getValue();
        }
      }
    }
    return null;
  }

  public static String getBrowser(HttpServletRequest request) {
    String header = request.getHeader("User-Agent");
    
    if (header == null) {
      return "";
    } 
    
    if (header.indexOf("MSIE") > -1) {
      return "MSIE";
    } 
    
    if (header.indexOf("Chrome") > -1 && !(header.indexOf("Firefox") > -1) && !(header.indexOf("Edge") > -1) && !(header.indexOf("OPR") > -1)) {
        return "Chrome";
    }
    
    if (header.indexOf("OPR") > -1) {
      return "Opera";
    } 
    
    if (header.indexOf("Firefox") > -1) {
      return "Firefox";
    } 
    
    if (header.indexOf("Edge") > -1) {
      return "Edge";
    } 
    
    if (header.indexOf("Safari") > -1) {
      return "Safari";
    } 
   
    
    
    else {
      return header;
    }
  }

  public static String getRequestURI(HttpServletRequest request) {
    Object forwardRequestUri = request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    if (forwardRequestUri != null) {
      return forwardRequestUri + "(" + request.getRequestURI() + ")";
    }
    return request.getRequestURI();
  }

  public static String getRemoteAddr(HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }
    return ip;
  }

  public static String getRequestBaseUrl(HttpServletRequest request) {
    String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
        + request.getContextPath();
    return path;
  }

  public static String getHeaderString(HttpServletRequest request) {
    Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames == null) {
      return null;
    }
    Map<String, String> headerMap = Maps.newLinkedHashMap();
    try {
      String headerName = null;
      while ((headerName = headerNames.nextElement()) != null) {
        headerMap.put(headerName, request.getHeader(headerName));
      }
    } catch (NoSuchElementException e) {
      return headerMap.toString();
    }

    return headerMap.toString();
  }
  
	public static String removeParameterFromURI(URI uri, String param) {
		UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUri(uri);
		return uriBuilder.replaceQueryParam(param, (Object[]) null).toUriString();
	}
	
  public static String getDeviceType(HttpServletRequest request) {
	  String userAgent = request.getHeader("User-Agent");
	  
	  //기기 구분
	  if(userAgent.indexOf("iPad") != -1 || userAgent.indexOf("iPhone") != -1) {
		  return "IOS";
	  }
	  
	  else if(userAgent.indexOf("Android") != -1) {
		  return "ANDROID";
	  }
	  
	  else {
		  return "PC";
	  }
	  
  }

}

 

ResponseUtil.java

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

public class ResponseUtil {
  public static void alertAndGo(HttpServletResponse response, String msg, String url)
      throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.getWriter().printf("<script>alert('%s', function(){location.href='%s';});</script>",
        msg, url);
  }

  public static void alertAndBack(HttpServletResponse response, String msg) throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.getWriter().printf("<script>alert('%s', function(){history.go(-1);});</script>", msg);
  }

  public static void write(HttpServletResponse response, String contents) throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.getWriter().print(contents);
  }
  public static void writeJson(HttpServletResponse response, String contents) throws IOException {
    response.setContentType("application/json; charset=UTF-8");
    response.getWriter().print(contents);
  }

  public static void addCookie(HttpServletResponse response, String key, String value)
      throws IOException {
    Cookie cookie = new Cookie(key, value);
    cookie.setSecure(true);
    cookie.setHttpOnly(true); //HttpOnly flag    
    cookie.setMaxAge(60 * 60 * 24 * 365);
    cookie.setPath("/");
    response.addCookie(cookie);
  }

  public static void wrapHtml(HttpServletResponse response, String contents) throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    StringBuffer sb = new StringBuffer();
    sb.append("<html>");
    sb.append("<body>");
    sb.append("<head>");
    sb.append("<meta charset=\"utf-8\">");
    sb.append("<meta http-equiv=\"content-type\" content=\"text/html;charset=UTF-8\" />");
    sb.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" />");
    sb.append(
        "<link href=\"/hpms/fonts/nanumbarungothic.css\" rel=\"stylesheet\" type=\"text/css\" />");
    sb.append(
        "<style>*{ font-family: 'Nanum Barun Gothic','돋움', '굴림', Dotum, Gulim, sans-serif;  font-size:13px; }</style>");
    sb.append("<script src=\"/hpms/js/jquery-2.0.2.min.js\"></script>");
    sb.append("<script>$(window).load(function(){parent.resizeContents();});</script>");
    sb.append("</head>");
    sb.append(contents);
    sb.append("</body>");
    sb.append("</html>");
    response.getWriter().print(sb.toString());
  }
}

 

StringUtils.java

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class StringUtils {
public static String encodeFileNm(String fileName, String browser) {

	    String encodedFilename = null;
	    if ("MSIE".equals(browser)) {
	      try {
	        encodedFilename = URLEncoder.encode(fileName, "UTF-8");
	      } catch (UnsupportedEncodingException e) {
	        log.error(e.getMessage());
	      }
	    } else if ("Firefox".equals(browser)) {
	      try {
	        encodedFilename =

	            "\"" + new String(fileName.getBytes("UTF-8"), "8859_1") + "\"";
	      } catch (UnsupportedEncodingException e) {
	    	  log.error(e.getMessage());
	      }
	    } else if ("Opera".equals(browser)) {
	      try {
	        encodedFilename =

	            "\"" + new String(fileName.getBytes("UTF-8"), "8859_1") + "\"";
	      } catch (UnsupportedEncodingException e) {
	    	  log.error(e.getMessage());
	      }
	    } else if ("Chrome".equals(browser)) {
	      StringBuffer sb = new StringBuffer();
	      for (int i = 0; i < fileName.length(); i++) {
	        char c = fileName.charAt(i);
	        if (c > '~') {
	          try {
	            sb.append(URLEncoder.encode("" + c, "UTF-8"));
	          } catch (UnsupportedEncodingException e) {
	        	  log.error(e.getMessage());
	          }
	        } else {
	          sb.append(c);
	        }
	      }
	      encodedFilename = sb.toString();
	    } else if ("Safari".equals(browser)) {
	      try {
	        encodedFilename =

	            "\"" + new String(fileName.getBytes("UTF-8"), "8859_1") + "\"";
	      } catch (UnsupportedEncodingException e) {
	    	  log.error(e.getMessage());
	      }
	    } else {
	      try {
	        encodedFilename = URLEncoder.encode(fileName, "UTF-8");
	      } catch (UnsupportedEncodingException e) {
	    	  log.error(e.getMessage());
	      }
	    }

	    return encodedFilename;
	}
 }

 

 

Service.java

/**
	 * 파일 조회 (파일).
	 *
	 * @param idx the idx
	 * @return the file object
	 */
	public File getFileObject(String idx);

 

ServiceImpl.java

@Override
		public File getFileObject(String idx) {
			FileInfo temp = getFile(idx);
			String logiPath = "";
			
			//썸네일 없을경우 기존이미지 보여주기
			if(temp.getThumbPath() == null || temp.getThumbNm() == null) {
				logiPath = temp.getPyscPath() +"/" + temp.getPyscNm();
			}
			
			//썸네일 있을경우
			else {
				logiPath = temp.getThumbPath() +"/" + temp.getThumbNm();
			}
			
			System.out.println("logiPath : " + logiPath);
			
			File imageFile = new File(logiPath);
			
			return imageFile;
		}
        
        
        @Override
		public FileInfo getFile(String seq) {
			// TODO Auto-generated method stub
			
			return fileMapper.selectFile(seq);
		}

 

fileMapper.java

/**
	 * Select file.
	 *
	 * @param seq the seq
	 * @return the file info
	 */
	FileInfo selectFile(String seq);

 

fileMapper.xml

<select id="selectFile" parameterType="java.lang.String"  resultType="fileInfo">
		SELECT
			*
		FROM
			TB_FILE
		WHERE
			USE_YN = 'Y'
		AND
			FILE_ID = #{value}
	</select>

'스프링' 카테고리의 다른 글

[1] Spring Boot 웹프로젝트 만들기  (0) 2019.09.28
[Spring] 파일업로드  (0) 2019.07.19
tiles-single jsp 페이지 ajax  (0) 2019.05.28
[Spring] lombok 설치  (0) 2019.05.20
자동 주석 설정  (0) 2019.04.26
복사했습니다!