괴발개발/Spring Framework

게시글 상세보기: 파일다운로드

moonday 2021. 8. 25. 18:32
jsp파일에서 a태그 href의 다운로드 링크주소 <%=request.getContextPath()%>/경로쓸거다쓰고/filename?${파일의경로가다들어있는파일이름}

*원래 업로드당시의 파일이름을 쓰면 안됨. 다운로드시 주소를 못찾아

 

컨트롤러 코드 

@Override
	public ResponseEntity<byte[]> downloadFile(String fileName) throws IOException {
		InputStream in = null;
	    ResponseEntity<byte[]> entity = null;
	    try{
	        HttpHeaders headers = new HttpHeaders();
	        in = new FileInputStream(uploadPath+fileName);

	        fileName = fileName.substring(fileName.indexOf("_")+1);
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	        headers.add("Content-Disposition",  "attachment; filename=\"" 
				+ new String(fileName.getBytes("UTF-8"), "ISO-8859-1")+"\"");
	        entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in),headers,HttpStatus.CREATED);
	    }catch(Exception e) {
	        e.printStackTrace();
	        entity = new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST);
	    }finally {
	        in.close();
	    }
	    return entity;
	}

 

FileInputStream은 파일을 읽어오는 메소드

.FileInputStream()을 사용하면 꼭 .close()를 쓸 것

in = new FileInputStream(uploadPath+fileName);

in.close();

참고블로그:https://aricode.tistory.com/2

 

.subString() 문자열 자르기

.subString(0) : 0번째문자열부터 끝까지 자름

.subString(1,4): 1번째 문자열에서 3번째문자열까지 자름

fileName = fileName.substring(fileName.indexOf("_")+1);

 

HttpHeaders의 객체를 이용해서 컨텐츠의 타입을 설정

특정 서브타입이 없는 텍스트 문서들에 대해서는 text/plain
특정 혹은 알려진 서브타입이 없는 이진 문서에 대해서는 application/octet-stream  사용
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

 

참고블로그: https://developer.mozilla.org/ko/docs/Web/HTTP/Basics_of_HTTP/MIME_types

 

 

"Content-Disposition" 에는 사용자가 다운로드 받을 때의 보여줄 파일 이름

headers.add("Content-Disposition",  "attachment; filename=\"" 
				+ new String(fileName.getBytes("UTF-8"), "ISO-8859-1")+"\"");

 

전송될 파일은 파일종류에 상관없이 byte[] 형태로 만들어 ResponseEntity 에 넣어줌

IOUtils : 입출력조작유틸리티 / FileUtils 파일시스템 유틸리티

entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in),headers,HttpStatus.CREATED);

 

출처: https://repacat.tistory.com/40

https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=0192141606&logNo=70177195454