본문 바로가기

JAVA

JAVA 파일 다운로드 구현 코드

728x90
반응형
SMALL

dFile = 파일의 이름

upDir = 파일의 경로

path = 파일의 경로와 이름

 

세가지 만 주의하면 파일 다운로드가 가능한, 소스 입니다.

@GetMapping("/fileDown")
	 public void fileDown(ModelMap model, 
			 			HttpServletRequest request, 
			 			HttpServletResponse response,
			 			CounselManualVO counselManualVO) throws Exception {

	  String dFile = counselManualVO.getFile_name(); //이름 받아오면 됨.
	  String upDir = "/data/uploads/"; //고정 경로인경우 직접 입력, 아닐경우 DB에서 경로 받아오기
	  String path = upDir+File.separator+dFile;
	  
	  File file = new File(path);

	  String userAgent = request.getHeader("User-Agent");
	  boolean ie = userAgent.indexOf("MSIE") > -1 || userAgent.indexOf("rv:11") > -1;
	  String fileName = null;
	  
	  if (ie) {
		  fileName = URLEncoder.encode(file.getName(), "utf-8");
	  } else {
		  fileName = new String(file.getName().getBytes("utf-8"),"iso-8859-1");
	  }
	  
	  response.setContentType("application/octet-stream");
	  response.setHeader("Content-Disposition","attachment;filename=\"" +fileName+"\";");
	  
	  FileInputStream fis=new FileInputStream(file);
	  BufferedInputStream bis=new BufferedInputStream(fis);
	  ServletOutputStream so=response.getOutputStream();
	  BufferedOutputStream bos=new BufferedOutputStream(so);
	  
	  byte[] data=new byte[2048];
	  int input=0;
	  while((input=bis.read(data))!=-1){
		  bos.write(data,0,input);
		  bos.flush();
	  }
	  
		 if(bos!=null) bos.close();
		 if(bis!=null) bis.close();
		 if(so!=null) so.close();
		 if(fis!=null) fis.close();
	 }

 끝

728x90
반응형
LIST

'JAVA' 카테고리의 다른 글

java 와치서비스  (1) 2023.11.01
자바 Math.random() 활용한 난수 생성  (0) 2023.03.14
String to int , int to String  (0) 2023.03.14
JAVA 와 Mysql 타입 매칭  (0) 2023.02.10
ArrayList 와 LinkedList 차이점  (0) 2022.04.17