@Autowired 	
ResourceLoader resourceLoader; 	 
// 파일의 위치 	
@Value("${file.path}") 	
private String file_Path; 

@RequestMapping("/fileDownload") 	
public ResponseEntity<InputStreamResource> download( 			
       @RequestParam(defaultValue = "test") String fName 			) throws IOException { 		 		
       System.out.println("fName = " + fName); 		
       
       // 파일 경로 		
       String path = file_Path + File.separator + fName; 		
       
       // 파일 존재 유무 		
       boolean fExist = _FileUtil.fileExistInfo(path); 		
       if(fExist) { 	 
       File file = new File(path); 	 
       String fileName = file.getName(); 	 
       
       // 파일 확장자 	 
       String ext = fileName.substring(fileName.lastIndexOf(".") + 1); 	 
       HttpHeaders header = new HttpHeaders(); 	 
       Path fPath = Paths.get(file.getAbsolutePath()); 	 	 
       header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+fileName); 	 
       header.add("Cache-Control", "no-cache, no-store, must-revalidate"); 	 
       header.add("Pragma", "no-cache"); 	 
       header.add("Expires", "0"); 	 	 
       
       // 대용량일 경우 resource3을 사용해야함 
       //	 ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(fPath )); 
       //	 Resource resouce2 = resourceLoader.getResource(path); 	 
       InputStreamResource resource3 = new InputStreamResource(new FileInputStream(file)); 	 	 
       return ResponseEntity.ok() 	 
       .headers(header) 	 
       .contentLength(file.length()) 	 
       .contentType(MediaType.parseMediaType("application/octet-stream")) 	 
       .body(resource3); 		
       } 		
return null; 	}

Content-Type: application/octet-stream

Content-Disposition: attachment; filename=<브라우저에서 저장할 파일>

Posted by rainbowpoint
,