웹 개발/Spring Boot
Spring Boot) resources 폴더 내 파일 다운로드
seungyoon
2021. 9. 11. 14:18
FileService.java
@Service("fileService")
public class FileService {
...
/**
* resources/{폴더 이름} 에 저장되어 있는 파일 다운로드
* @param fileName,dirName
* @return ResponseEntity<Resource>
*/
public ResponseEntity<Resource> downloadResourceFile(String fileName, String dirName) throws IOException{
Path filePath = Paths.get(File.separatorChar + dirName, File.separatorChar + fileName);
Resource resource = new InputStreamResource(getClass().getResourceAsStream(filePath.toString()));
logger.info("Success download file in resources directory : " + filePath);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.cacheControl(CacheControl.noCache())
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName + "")
.body(resource);
}
...
}
FileController.java
@Controller
@RestController
public class FileController {
@Autowired
FileService fileService;
...
@GetMapping(value = "resource-file-download/{fileName}/{dirName}")
public ResponseEntity<Resource> resourceFileDownload(@PathVariable String fileName, @PathVariable String dirName) throws IOException{
return fileService.downloadResourceFile(fileName, dirName);
}
}
** resource/dirName/fileName 이렇게 된 상황!