我有一個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。
我很確定我錯過了一些非常小的東西,但作爲一名初級開發者,我仍然無法弄清楚。
你是不是想將文件發送的HTTP響應還是什麼?抱歉,我無法理解你的代碼。 – Rafa
是的,這就是我想要做的。 – Slim
但是您將文件保存在文件系統中!如果你想通過HTTP發送文件,你必須將字節寫入'OutputStream',你從HTTP響應中獲得。 – AlexR