2013-11-04 37 views
2

我想讓用戶從服務器上下載文件。 我使用ServletOutputStream的在我的控制器(這裏是代碼)如何讓用戶使用ajax成功方法下載文件?

@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它具有文件的內容的數據,但我希望這個文件被下載到用戶,而不僅僅是打印。如何讓用戶將數據保存爲文件?

+0

http://stackoverflow.com/questions/6722716/how-to-download-file-from-server-using-jquery-ajax-and-spring-mvc-3 – hgoebl

回答

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

        } 
+0

你的意思是路徑文件?我沒有該文件的網址。我不瞭解這個ServletOutputStream的工作人員,那是幹什麼的?我應該不知何故獲得ServletOutputStream的url?我的主要問題是,我不知道如何生成網址到該文件 – user2944769

+0

在您的服務器文件夾路徑將是url.if你沒有hav url意味着用戶將如何從服務器下載文件? –

+0

該文件不在服務器文件夾中... – user2944769

-1

您無法強制使用Ajax進行文件下載。由於許多安全原因,Javascript無法將文件保存到用戶的計算機。解決方案是製作一個控制器,它可以爲下載頁面提供服務,並使您的success函數將window.location更改爲它。

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

假設data只是URL。您可以使其更健壯,以使用JSON或任何其他響應格式,您可以從中檢索鏈接。

-1

請勿使用ajax。而是提供一個下載鏈接。

<a href="URL_TOCONTROLLER_METHOD" download>Click To Download</a> 
相關問題