복붙노트

[SPRING] Spring boot rest service에서 파일을 다운로드한다.

SPRING

Spring boot rest service에서 파일을 다운로드한다.

스프링 부트 레스트 서비스에서 파일을 다운로드하려고합니다.

@RequestMapping(path="/downloadFile",method=RequestMethod.GET)
    @Consumes(MediaType.APPLICATION_JSON_VALUE)
    public  ResponseEntity<InputStreamReader> downloadDocument(
                String acquistionId,
                String fileType,
                Integer expressVfId) throws IOException {
        File file2Upload = new File("C:\\Users\\admin\\Desktop\\bkp\\1.rtf");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        InputStreamReader i = new InputStreamReader(new FileInputStream(file2Upload));
        System.out.println("The length of the file is : "+file2Upload.length());

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

브라우저에서 파일을 다운로드하려고 시도하면 다운로드가 시작되지만 항상 실패합니다. 다운로드에 실패한 서비스에 문제가 있습니까?

해결법

  1. ==============================

    1.옵션 1은 InputStreamResource를 사용합니다.

    옵션 1은 InputStreamResource를 사용합니다.

    @RequestMapping(path = "/download", method = RequestMethod.GET)
    public ResponseEntity<Resource> download(String param) throws IOException {
    
        // ...
    
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
    
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }
    

    Option2는 InputStreamResource의 문서로 제시 - ByteArrayResource를 사용하여 :

    @RequestMapping(path = "/download", method = RequestMethod.GET)
    public ResponseEntity<Resource> download(String param) throws IOException {
    
        // ...
    
        Path path = Paths.get(file.getAbsolutePath());
        ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
    
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }
    
  2. ==============================

    2.또한 InputStream에서 응답 OutputStream으로 동일한 복사 바이트를 얻을 수 있습니다. 이를 위해 컨트롤러를 다음과 같이 정의하십시오.

    또한 InputStream에서 응답 OutputStream으로 동일한 복사 바이트를 얻을 수 있습니다. 이를 위해 컨트롤러를 다음과 같이 정의하십시오.

    참조 - 봄 부팅 파일 다운로드 예제

  3. from https://stackoverflow.com/questions/35680932/download-a-file-from-spring-boot-rest-service by cc-by-sa and MIT license