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


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.setHeader("Content-Disposition", "attachment; filename=file.zip");
      ServletOutputStream responseOutputStream = response.getOutputStream();
      org.apache.commons.io.IOUtils.copy(fileContent, responseOutputStream);
    } 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:

  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";

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.setHeader("Content-disposition", "attachment; filename=" + fileName);
    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 Unity发布gzip压缩的webgl之后让浏览器可以正常显示画面
  • ¥15 有没有人知道这种提示怎么关?现在不做ts项目了不知道咋关了,求解,现在我以前的js项目都是这种提示了
  • ¥15 为什么mysql做了碎片化处理data_free还是很高
  • ¥15 single positional indexer is out-of-bounds
  • ¥15 LSTM 模型数据量需要多少?
  • ¥15 mysql数据抓包开发报表
  • ¥15 linux系统下安装office打不开
  • ¥20 rsync脚本分发错误,文件不齐全
  • ¥15 labview顺序结构与时间延时
  • ¥15 脚本求解,源于数据库脚本变量筛选。