복붙노트

[SPRING] Spring Service에서 AJAX GET을 사용하여 파일 다운로드

SPRING

Spring Service에서 AJAX GET을 사용하여 파일 다운로드

요청한 파일로 다운로드를 자동으로 시작하는 서비스를 구현하려고합니다.

이것은 내 AJAX 전화입니다.

function downloadFile(fileName) {
  $.ajax({
    url : SERVICE_URI + "files/" + fileName,
    contentType : 'application/json',
    type : 'GET',
    success : function (data)
    {
      alert("done!");
    },
    error: function (error) {
      console.log(error);
    }
  });
}

이것은 내 스프링 서비스 방법 GET입니다.

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
public void getFile(@PathVariable("file_name") String fileName,
                    HttpServletResponse response) {
    try {
        // get your file as InputStream
        FileInputStream fis = new FileInputStream( fileName + ".csv" );
        InputStream is = fis;
        // copy it to response's OutputStream
        ByteStreams.copy(is, response.getOutputStream());
        response.setContentType("text/csv");
        response.flushBuffer();
    } catch (IOException ex) {
        throw new RuntimeException("IOError writing file to output stream");
    }

}

클라이언트가 서버에서 기존 파일을 요청하면 AJAX success () 메소드가 실행되지만 파일이 다운로드되지도 않습니다. 내가 잘못하고 있습니까?

해결법

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

    1.ajax를 사용하지 말고 window.location.href를 파일의 URL로 설정하고 서버 스크립트에서 http 컨텐츠 처리 헤더를 설정하여 브라우저가 파일을 저장하도록하십시오.

    ajax를 사용하지 말고 window.location.href를 파일의 URL로 설정하고 서버 스크립트에서 http 컨텐츠 처리 헤더를 설정하여 브라우저가 파일을 저장하도록하십시오.

    function downloadFile(fileName) {
      window.location.href = SERVICE_URI + "files/" + fileName;
    }
    
  2. from https://stackoverflow.com/questions/27785819/downloading-a-file-using-ajax-get-from-spring-service by cc-by-sa and MIT license