繁体   English   中英

如何让用户以ajax成功的方式下载文件?

[英]How to let user download a file in ajax success method?

我试图让用户从服务器下载文件。 我在控制器中使用ServletOutputStream(代码如下)

@RequestMapping(value = "/get-backup-file", method = RequestMethod.GET)
@ResponseBody
public void getBackupFile(
    HttpServletRequest request, 
    HttpServletResponse response) throws MalformedURLException, IOException {

    File backupFile = new File("PATH_TO_FILE");        

    ServletOutputStream out = response.getOutputStream();

    response.setContentType("application/octet-stream");
    response.setContentLength((int)backupFile.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + "database backup" + "\"");

    FileInputStream in = new FileInputStream(backupFile);
    byte[] buffer = new byte[4096];

    int length;
    while( (length = in.read(buffer) ) > 0) {
        out.write(buffer, 0, length);
    }
    in.close();
    out.flush();        
} 

我的客户端看起来像这样:

      $.ajax({
        url: 'URL_TOCONTROLLER_METHOD',
        contentType: "application/octet-stream; charset=utf-8",
        type: 'GET',
        success: function(data) {
            console.log(data);
        },
        error: function(data) {   
            console.log("error");
        }
    });

当我console.log数据时,它具有文件的内容,但是我希望将此文件下载给用户,而不仅仅是打印。 如何使用户将数据另存为文件?

您必须发送文件存储的路径并打开成功功能,然后用户才能下载它

如果成功就是那样

{"status":"success","path":"temp\/Vehicle_Units_2013_11_04.xls"}

脚本是

success: function(msg)
                  {
                      if(msg.status=="session-expired")
                      {
                      window.location.replace("index.jsp");
                      }
                      if(msg.status=="success")
                      {
                          window.open(msg.path);
                      }

                  }

您不能使用Ajax强制下载文件。 出于多种安全原因,JavaScript无法将文件保存到用户的计算机。 解决方案是使一个控制器为下载页面提供服务,并让您的success功能将window.location更改为该控制器。

success : function (data) {
    window.location = data;
}

假设data只是URL。 您可以使其更加健壮,以使用JSON或任何其他可以从中检索链接的响应格式。

不要使用ajax。 而是提供下载链接。

<a href="URL_TOCONTROLLER_METHOD" download>Click To Download</a>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM