1. 程式人生 > >java伺服器檔案下載到本地

java伺服器檔案下載到本地

前言

我實現了一個生成excel的功能,讓使用者在訪問伺服器點選匯出按鈕時下載到使用者本地。這就不能只是簡單的java io寫出了,總不能寫出到伺服器本地了吧,使用者本地一臉懵逼。怎麼返回檔案給訪問網頁的使用者?通過response返回檔案資料。

正文

邏輯是:使用者點選按鈕—>前臺提交—>後臺處理—>返回檔案
首先我們前臺需要一個from表單提交事件

 <form id="dailyCountThree" method="post" 
 	action="exportexcellist.action?cmd=function" >
 	...
</form>

作用就是點選按鈕後跳轉到指定action方法,在action完成生成檔案的處理之後呢,將檔案想辦法通過respone給返回回去。

//即將下載的檔名字
String filename =  fileName + time + ".xls";
//將檔名字編碼
filename = URLEncoder.encode(filename,"UTF-8");
//拿到當前respone,很關鍵
HttpServletResponse response = 
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
//通過response得到輸出流
OutputStream os=response.getOutputStream();
//清除緩衝區中存在的任何資料以及狀態程式碼和標頭
response.reset();
response.setContentType("application/x-download");
// 設定輸出檔案頭
response.addHeader("Content-Disposition","attachment;filename=" + filename);
// 定義輸出型別
response.setContentType("application/msexcel");
//通過response得到的輸出流os將檔案輸出
os.write(...)

這裡需要注意的是response.reset()方法,介紹如下:

Clears any data that exists in the buffer as well as the status code and headers.
If the response has been committed, this method throws an IllegalStateException.
清除緩衝區中存在的任何資料以及狀態程式碼和標頭。
如果響應已提交,則此方法引發IllegalStateException異常。