通过ajax下载文件

Eve*_*0id 2 javascript java ajax jquery spring

我需要通过ajax从服务器下载文件.问题是该文件未存储在服务器上.我的基于java的后端自动从请求参数生成文件并在响应正文中返回它:

  @RequestMapping(value = "/download", method = RequestMethod.GET)
  public void download(@RequestParam String description, @RequestParam Long logId, HttpServletResponse response) {
    try {
      InputStream fileContent = // getting file as byte stream
      response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
      response.setHeader("Content-Disposition", "attachment; filename=file.zip");
      ServletOutputStream responseOutputStream = response.getOutputStream();
      org.apache.commons.io.IOUtils.copy(fileContent, responseOutputStream);
      response.flushBuffer();
    } catch (IOException e) {
      logger.error("Attempt to download file failed", e);
    }
  }
Run Code Online (Sandbox Code Playgroud)

所以我需要处理它并允许用户下载文件.我的客户端包含这个:

$.ajax({
  type: "GET",
  url: "/download",
  data: {
    description: "test",
    logId: 123
  },
  success: function(data) {
    var blob = new Blob([data]);
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = "file.zip";
    link.click();
  }
})
Run Code Online (Sandbox Code Playgroud)

控制器返回文件,但没有任何反应.我究竟做错了什么?

Tim*_*sen 7

不要进行AJAX调用,而是将窗口的href设置为指向用于下载文件的URL.然后更改响应的内容类型,并将响应application/x-download的标头设置为Content-disposition:

response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
response.flushBuffer();

function download(fileName) {
    window.location.href = "/download?description=test&logId=123";
}
Run Code Online (Sandbox Code Playgroud)

另外,看看这个SO帖子,它解决了与你的问题类似的问题.

  • 好的,但是如果我想要发布请求而不是获取并传递 looong 字符串参数,我需要做什么? (2认同)
  • 你的答案在我的具体案例中完美运作.我只是想深入挖掘. (2认同)