从Spring Service使用AJAX GET下载文件

时间:2021-11-02 09:55:41

I'm trying to implement a Service that automatically starts a download with the requested file.

我正在尝试实现一个自动开始下载所请求文件的服务。

This is my AJAX call:

这是我的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);
    }
  });
}

and this is my Spring Service method GET:

这是我的Spring Service方法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");
    }

}

When my client requests the existing file from the server, the AJAX success() method is executed but the file is not even downloading. Am I doing anything wrong?

当我的客户端从服务器请求现有文件时,执行AJAX success()方法,但文件甚至没有下载。我做错了吗?

1 个解决方案

#1


6  

Don't use ajax, just set window.location.href to the url of the file and set the http content disposition header in your server script to force the browser to save the file.

不要使用ajax,只需将window.location.href设置为文件的url,并在服务器脚本中设置http内容处置标头以强制浏览器保存文件。

function downloadFile(fileName) {
  window.location.href = SERVICE_URI + "files/" + fileName;
}

#1


6  

Don't use ajax, just set window.location.href to the url of the file and set the http content disposition header in your server script to force the browser to save the file.

不要使用ajax,只需将window.location.href设置为文件的url,并在服务器脚本中设置http内容处置标头以强制浏览器保存文件。

function downloadFile(fileName) {
  window.location.href = SERVICE_URI + "files/" + fileName;
}