通过ajax下载文件 [英] File download through ajax

查看:163
本文介绍了通过ajax下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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

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

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

这篇关于通过ajax下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆