最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - How to let user download a file in ajax success method? - Stack Overflow

programmeradmin4浏览0评论

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

@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?

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

@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?

Share Improve this question asked Nov 4, 2013 at 10:16 user2944769user2944769 512 gold badges2 silver badges7 bronze badges 1
  • stackoverflow./questions/6722716/… – hgoebl Commented Nov 4, 2013 at 10:19
Add a ment  | 

3 Answers 3

Reset to default 3

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

                  }

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

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

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

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

<a href="URL_TOCONTROLLER_METHOD" download>Click To Download</a>
发布评论

评论列表(0)

  1. 暂无评论