> Java > java지도 시간 > 본문

Spring Boot REST 서비스에서 파일을 성공적으로 다운로드하는 방법은 무엇입니까?

Barbara Streisand
풀어 주다: 2024-10-28 07:53:02
원래의
927명이 탐색했습니다.

How to Successfully Download Files from a Spring Boot REST Service?

Spring Boot REST 서비스에서 파일 다운로드

Spring Boot에서는 REST 서비스를 활용하여 파일을 다운로드할 수 있습니다. 그러나 다운로드가 실패하면 일반적인 문제가 발생합니다.

이 오류가 발생하는 서비스 구현은 다음과 같습니다.

<code class="java">@RequestMapping(path="/downloadFile",method=RequestMethod.GET)
public  ResponseEntity<InputStreamReader> downloadDocument(
                String acquistionId,
                String fileType,
                Integer expressVfId) throws IOException {
    // Code for file acquisition...

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

    return ResponseEntity.ok().headers(headers).contentLength(file2Upload.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(i);
}</code>
로그인 후 복사

이 문제를 해결하려면 다음 해결 방법을 고려하세요.

옵션 1: InputStreamResource 사용

InputStreamResource를 사용하여 파일의 InputStream 래핑:

<code class="java">InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

return ResponseEntity.ok()
        .headers(headers)
        .contentLength(file.length())
        .contentType(MediaType.APPLICATION_OCTET_STREAM)
        .body(resource);</code>
로그인 후 복사

옵션 2: ByteArrayResource 사용

InputStreamResource 문서에서 제안한 대로 ByteArrayResource를 사용하는 것이 더 효율적일 수 있습니다.

<code class="java">Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

return ResponseEntity.ok()
        .headers(headers)
        .contentLength(file.length())
        .contentType(MediaType.APPLICATION_OCTET_STREAM)
        .body(resource);</code>
로그인 후 복사

이러한 솔루션을 통합하면 Spring Boot REST 서비스에서 파일을 성공적으로 다운로드할 수 있습니다.

위 내용은 Spring Boot REST 서비스에서 파일을 성공적으로 다운로드하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!