2013-07-03 65 views
1

我有一個servlet女巫產生.xls文件,然後它發送生成的文件以供用戶下載使用下面的代碼:奇怪的servlet響應問題

// Write the output to a file 
Calendar currentDate = Calendar.getInstance(); 
SimpleDateFormat formatter= 
new SimpleDateFormat("yyyy_MMM_dd"); 
String dateNow = formatter.format(currentDate.getTime()); 

String path = "webapps/myapp/exports/"; 
String fileName = ("Table_export_"+ dateNow + ".xls"); 

FileOutputStream fileOut = new FileOutputStream(path+fileName); 
wb.write(fileOut); 
fileOut.close(); 
response.setContentType("application/vnd.ms-excel"); 
response.setHeader("Content-Disposition","attachment;filename="+fileName); 

文件被保存在服務器上用大小爲5 kb,但在瀏覽器對話框以及選擇保存或打開後,文件爲空,大小爲0 kb。我不明白什麼是錯的。

我與這個問題約2小時沒有成功的戰鬥。我試圖設置完整路徑:

response.setHeader("Content-Disposition","attachment;filename="path+fileName); 

但是,我得到一個具有奇怪名稱的文檔,它也是0 kb。

我很確定我錯過了一些非常小的東西,但作爲一名初級開發者,我仍然無法弄清楚。

+1

你是不是想將文件發送的HTTP響應還是什麼?抱歉,我無法理解你的代碼。 – Rafa

+0

是的,這就是我想要做的。 – Slim

+1

但是您將文件保存在文件系統中!如果你想通過HTTP發送文件,你必須將字節寫入'OutputStream',你從HTTP響應中獲得。 – AlexR

回答

2

既然你已經有一個可以將文件寫入到輸出流的方法,你可以簡單地改變你的代碼這種方式將其發送給用戶:

Calendar currentDate = Calendar.getInstance(); 
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MMM_dd"); 
String dateNow = formatter.format(currentDate.getTime()); 

String fileName = ("Table_export_"+ dateNow + ".xls"); 

response.setContentType("application/vnd.ms-excel"); 
response.setHeader("Content-Disposition","attachment;filename="+fileName); 

OutputStream outputStream = response.getOutputStream(); 
try { 
    wb.write(outputStream); 
} finally { 
    outputStream.close(); 
} 

它不會被保存在服務器上HDD雖然。

方法HttpServletResponse#getOutputStream()允許您訪問將被髮送回客戶端的字節流。

+0

非常感謝!這是我正在尋找的東西!你搖滾!再次感謝! – Slim

0

當您使用的格式 -

String path = "webapps/myapp/exports/"; 
String fileName = ("Table_export_"+ dateNow + ".xls"); 
... 
response.setHeader("Content-Disposition","attachment;filename="path+fileName); 

當時的文件名 「的webapps%2Fmyapps%2Fexports%2fTable_export _.... XLS」?

阿爾斯文件大小將是零,因爲你沒有把任何數據文件