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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程