Spring 파일 다운로드 기능 구현시 한글깨짐 현상 해결법

HyunJunSon·2024년 5월 1일
0

문제상황

  • 아래 코드와 같이 파일 다운로드 기능을 구현하던 중, 한글파일의 경우, 다운로드가 되지 않고, 바이너리 파일(사진파일임)이 열리는 현상이 나타남.
@GetMapping("/attach/{itemId}")
    public ResponseEntity<Resource> downloadAttach(@PathVariable Long itemId) throws MalformedURLException {
        Item item = itemRepository.findById(itemId);
        String storeFileName = item.getAttachFile().getStoreFileName();
        String uploadFileName = item.getAttachFile().getUploadFileName();

        UrlResource urlResource = new UrlResource("file:" + fileStore.getFullPath(storeFileName));
        log.info("uploadFileName={}", uploadFileName);

        String encodedUploadFile = UriUtils.encode(uploadFileName, StandardCharsets.UTF_8);
        String contentDisposition = "attachment; filename=\"" + encodedUploadFile + "\"";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);


        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                .body(urlResource);세요



해결법

  • 문제의 원인은, 파일명의 encoding이 이루어지지 않아서 임
String encodedUploadFile = UriUtils.encode(uploadFileName, StandardCharsets.UTF_8);
  • UrlUtils 에 있는 encoding 함수를 활용해서 encoding후 적용하니 잘나옴

Tip

  • 파일명이나 URL에 한글명을 다룰때는 항상 encoding에 신경써야 한다.
  • UriUtil 기억해두면 유용한 Util
profile
즐겁게 공부하고 사람들에게 도움을 주는 개발자가 되고 싶습니다.

0개의 댓글