본문 바로가기
Web

자바 웹, 파일 다운로드 구현

by 19810721 2020. 3. 28.
    @GetMapping("/download/{attatchFileId}")
    public ResponseEntity downloadFileFromLocal(@PathVariable String attatchFileId) throws FileNotFoundException {

        String fileBasePath = "C:/upload/";

        log.debug(attatchFileId);

        // FileService
        Optional<AttachFile> attachFile = tipsFileService.getAttachFilebyAttachFileId(Long.parseLong(attatchFileId));

        String fileName = fileBasePath + attachFile.get().getFilePhysicalName();

        Path path = (Path) Paths.get(fileName);

        File file = new File(fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Content-Disposition", "attachment; filename=" + attachFile.get().getFileLogicalName());

        InputStreamReader i = new InputStreamReader(new FileInputStream(file));
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

        return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(resource);
    }

지난 글 까지는 웹 브라우저에서 파일을 업로드 하고 그 업로드 한 파일을 DB 에 어떻게 효율적으로 저장해 두는가를 목표로 작업을 했다. 이번 글에서는 그렇게 올라간 파일과 DB 내용을 기반으로 웹 브라우저가 다운로드를 받은 방법을 알아보고자 한다.

 

@GetMapping("/download/{attatchFileId}")  

 

파일을 다운로드 받을 때는 역시 간단하게 GET 으로 리소스를 요청하기로 정하고, 여기서는 파일이 저장된 id 값을 요청값으로 한다고 치자.

 

파일이 저장된 위치를 정해주고, DB 를 통해 파일 정보를 가져온 후, 물리적 파일 경로값과 파일이 저장된 위치값의 조합으로 실제 파일이 저장된 Path 를 구하고, HTTP 응답을 위한 헤더를 생성 후, 미디어 타입 application/octet-stream 으로 클라이언트로 넘겨주면 브라우저는 헤더에서 설정한 파일명을 기반으로 다운로드가 시작된다.

 

아주 간단한 동작이지만, 이렇게 하면 html img tag 에 src 속성으로 해당 Get 리소스의 URI 를 ID 를 바꿔가며 마음 껏 적어도 static resources 처럼 활용이 가능하다는 장점이 있고,  테스트도 무탈하게 진행됨을 확인했다.

 

물론 외부에 공개가 되면 안되는 자료들이거나 로그인 사용자의 권한에 따라 접근이 달라져야 한다면 해당 로직을 추가하면 된다.

 

이렇게 해서 웹 브라우저에서 파일을 올리고, 저장하고, 저장된 파일을 다운로드를 간단하게 할 수 있는 내용을 살펴봤다. 나도 그러하듯 이걸 그대로 사용하기 보다는 본인의 상황에 맞게 잘 응용하여 사용한다면 시행착오를 줄이고 개발에 대한 고민을 덜 수 있기를 바란다.

 

컴퓨터와 대화하는 건 마치....