화면에서 파일을 클릭하면 다운로드를 받고 싶을 때
view 화면
<div id="downloadList" class="mt-1 text-center">
<span class="attachment" th:each="a : *{attachments}">
<input type="hidden" name="attachments" th:value="${a.id}" th:field="*{attachments}"/>
<a class="text-black" th:href="|@{/attachment/}${a.id}|">
<div class="file-name" th:text="${a.fileName}"></div>
</a>
</span>
</div>
연결이 /attachment/{id}로 되어 있으니 controller를 생성
AttachmentController
@RestController
@RequestMapping("/attachment")
@RequiredArgsConstructor
public class AttachmentController {
@NonNull
private final AttachmentService attachmentService;
@GetMapping(value = "/{id}", produces = "application/octet-stream")
public ResponseEntity attachment(@PathVariable("id") Long id) throws IOException {
Attachment attachment = attachmentService.findById(id).orElseThrow(DataNotFoundException::new);
File file = new File(attachment.getFilePath());
if (file.exists() && file.length() > 0) {
byte[] bytes = FileUtils.readFileToByteArray(file);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentLength(bytes.length);
httpHeaders.set("Content-Disposition",
"attachment; filename=\"" + attachment.getEncodedFileName() + "\";");
httpHeaders.set("Content-Transfer-Encoding", "binary");
httpHeaders.setContentType(MediaType.valueOf(Files.probeContentType(file.toPath())));
return new ResponseEntity(bytes, httpHeaders, HttpStatus.OK);
}
return ResponseEntity.notFound().build();
}
}
해당 controller 함수에 맞게 repository랑 service 구현
AttachmentRepository
@Repository
public interface AttachmentRepository extends JpaRepository<Attachment, Long> {
}
AttachmentService
@Service
@RequiredArgsConstructor
public class AttachmentService {
@NonNull
private final AttachmentRepository attachmentRepository;
@Cacheable(value = "attachment", key = "#id")
public Optional<Attachment> findById(Long id) {
return attachmentRepository.findById(id);
}
@CacheEvict(value = "attachment", key = "#attachment.id")
public Attachment save(Attachment attachment) {
return attachmentRepository.save(attachment);
}
}
위의 과정을 거치면 파일 클릭시 다운로드 가능!!
'Web > Spring' 카테고리의 다른 글
[Login구현] 사용자 등록하기(Register) (0) | 2021.08.10 |
---|---|
[Login구현] login-logout구현(setting) (0) | 2021.08.10 |
[MultipartFile] 첨부파일 업로드 (0) | 2021.08.06 |
[properties] server.port vs server.http.port (0) | 2021.08.06 |
[ERROR] 유의해야 할 점 (0) | 2021.08.06 |