weixin_33716557 2016-03-21 14:42 采纳率: 0%
浏览 146

通过Ajax下载文件

I need to download file from server via ajax. The problem is that the file is not stored on server. My java-based backend automatically generates file from request parameters and returns it in response body:

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

So i need to handle it and allow user to download file. My client side contains this:

$.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();
  }
})

Controller returns file, but then nothing happens. What am i doing wrong?

  • 写回答

2条回答 默认 最新

  • weixin_33691817 2016-03-21 14:52
    关注

    Don't make an AJAX call, but rather set the window's href to point to URL for downloading the file. Then change the content type of the response to application/x-download and set the header of the response to be 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";
    }
    

    Also, have a look at this SO post which addresses a similar problem to the one you have.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算