화면에서 파일을 클릭하면 다운로드를 받고 싶을 때

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);
  }
}

 

위의 과정을 거치면 파일 클릭시 다운로드 가능!!

+ Recent posts