이미지 클릭 시 display or download

전승원·2021년 1월 20일
0

Spring controller에서 이미지 download or display in a new tab 하는 방법?

출처: https://stackoverflow.com/questions/45767895/opening-a-file-in-browser-in-a-new-tab-rather-than-downloading-it

anchor 태그 혹은 form 태그에 아래와 같이

<a target="_blank" th:href="@{/file/view(fileId=*{file.fileId})}">

target="_blank" 를 붙여주면 새 탭에서 download or display 실행.

 @GetMapping(value = "/view")
    public ResponseEntity<byte[]> viewFile(@RequestParam("fileId") Integer fileId) {
        byte[] image = fileService.getByFileId(fileId).getFileData();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Disposition", "inline; filename=\"" + fileId + ".jpg\"");
        headers.setContentLength(image.length);
        headers.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<byte[]>(image, headers, HttpStatus.OK);
    }

버튼 클릭 시, 위와 같이 headers.set() 에 "Content-Disposition", "inline; ..."

이렇게 "inline"을 넣어주면 display 실행
그 외의 "anything"을 넣어주면 download 실행.

profile
No pleasure, No gain

0개의 댓글