파일 리소스를 읽어오는 방법
https://velog.io/@jsj3282/IoC-%EC%BB%A8%ED%85%8C%EC%9D%B4%EB%84%88-6
https://velog.io/@jsj3282/Resource-%EC%B6%94%EC%83%81%ED%99%94
파일 다운로드 응답 헤더에 설정할 내용
파일의 종류(미디어 타입) 알아내는 방법
<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-core -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>1.26</version>
</dependency>
ResponseEntity
@GetMapping("/file/{filename}")
@ResponseBody
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) throws IOException {
Resource resource = resourceLoader.getResource("classpath:" + filename); File file = resource.getFile();
Tika tika = new Tika();
String type = tika.detect(file);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachement; filename=\"" + resource.getFilename() + "\"")
.header(HttpHeaders.CONTENT_TYPE, type)
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()))
.body(resource);
}
resources 디렉터리 아래 test.jpg 파일 추가
@Controller
public class FileController {
@Autowired
private ResourceLoader resourceLoader;
@GetMapping("/file")
public String fileUploadForm(Model model){
return "files/index";
}
@PostMapping("/file")
public String fileUpload(@RequestParam MultipartFile file,
RedirectAttributes attributes){
// save
System.out.println("file name : " + file.getName());
System.out.println("file original name : " + file.getOriginalFilename());
String message = file.getOriginalFilename() + " is uploaded";
attributes.addFlashAttribute("message", message);
return "redirect:/file";
}
@GetMapping("/file/{filename}")
// @ResponseBody
public ResponseEntity<Resource> fileDownload(@PathVariable String filename) throws IOException {
Resource resource = resourceLoader.getResource("classpath:" + filename);
File file = resource.getFile();
Tika tika = new Tika();
String mediaType = tika.detect(file);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachement; filename=\"" + resource.getFilename() + "\"")
.header(HttpHeaders.CONTENT_TYPE, mediaType)
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()))
.body(resource);
}
}
참고