如何让用户在ajax成功方法中下载文件?

时间:2013-11-04 10:16:07

标签: java javascript file spring-mvc

我试图让用户从服务器下载文件。 我在我的控制器中使用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中获取文件内容的数据时,我希望将该文件下载给用户,而不仅仅是打印。如何让用户将数据保存为文件?

3 个答案:

答案 0 :(得分:3)

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

如果成功就是那样

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

                  }

答案 1 :(得分:-1)

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

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

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

答案 2 :(得分:-1)

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

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