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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19765566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:01:51  来源:igfitidea点击:

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

javajavascriptfilespring-mvc

提问by user2944769

I'm trying to let user download a file from server. I use ServletOutputStream in my controller (here is the code)

我试图让用户从服务器下载文件。我在控制器中使用 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();        
} 

My client side looks like this:

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

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

when I console.log the data it has the content of the file, but I want this file to be downloaded tu the user, not just printed. how can make let user to save the data as file?

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

回答by Sridhar R

You have to send path where the file stored and open its on success function,then user can download it

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

if success is like that

如果成功就是这样

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

script is

脚本是

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

                  }

回答by Sotirios Delimanolis

You cannot force a file download with Ajax. Javascript cannot save files to the user's computer for a number of security reasons. The solution is to make a controller which serves the download page and have your successfunction change the window.locationto it.

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

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

assuming datais just the URL. You can make this more robust to use JSON or any other response format from which you can retrieve the link.

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

回答by AJcodez

Don't use ajax. Instead provide a download link.

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

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