
Spring Boot Rest Service에서 파일 다운로드: 다운로드 실패 문제 해결
이 문서에서는 다음을 통해 파일을 다운로드하려고 할 때 발생하는 문제를 해결합니다. 스프링 부트 REST 서비스. 브라우저에서 다운로드가 시작되었음에도 불구하고 프로세스가 지속적으로 실패합니다. 다음은 문제 분석과 가능한 해결 방법입니다.
서비스 방법:
제공된 코드는 파일 다운로드를 담당하는 서비스 방법을 보여줍니다.
1 2 3 4 5 6 7 8 9 10 11 12 | <code class = "java" >@RequestMapping(path= "/downloadFile" ,method=RequestMethod.GET)
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));
return ResponseEntity.ok().headers(headers).contentLength(file2Upload.length())
.contentType(MediaType.parseMediaType( "application/octet-stream" ))
.body(i);
}</code>
|
로그인 후 복사
옵션 1: InputStreamResource 활용
제공된 코드는 파일에서 InputStreamReader를 생성하고 이를 ResponseEntity와 함께 반환합니다. 그러나 spring-core 라이브러리의 InputStreamResource를 사용하는 것이 좋습니다. 이 구현은 스트림용 리소스를 제공하여 다운로드 프로세스 중에 스트림의 적절한 처리를 보장합니다.
1 2 3 4 5 6 7 8 9 | <code class = "java" >@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.APPLICATION_OCTET_STREAM)
.body(resource);
}</code>
|
로그인 후 복사
옵션 2: ByteArrayResource 사용
Spring 문서에서는 제안합니다. InputStreamResource 대신 ByteArrayResource를 활용합니다. 이 리소스 유형을 사용하려면 전체 파일을 바이트 배열로 읽어서 여기에서 리소스를 생성해야 합니다. 이 접근 방식은 작은 파일의 성능 향상과 같은 특정 시나리오에서 유리할 수 있습니다.
1 2 3 4 5 6 7 8 9 10 | <code class = "java" >@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.APPLICATION_OCTET_STREAM)
.body(resource);
}</code>
|
로그인 후 복사
이러한 옵션 중 하나를 구현하면 다운로드 실패 문제가 해결되어 Spring Boot를 통해 원활한 파일 다운로드가 가능해집니다. REST 서비스입니다.
위 내용은 브라우저가 프로세스를 시작하는데도 불구하고 Spring Boot REST 서비스 다운로드가 실패하는 이유는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!