使用Firefox時,用戶單擊下載鏈接時即時打開下載對話框,但我無法使IE在顯示「另存爲」對話框之前在Writer上調用close() 。另存爲與IE的對話框僅在編輯器關閉後纔打開
我不能讓初始文件下載大小,因爲它是動態生成的。
ServletOutputStream os = null;
Writer writer = null;
try {
os = response.getOutputStream(); // response is from an input param HttpServletResponse
response.setHeader("Content-Disposition", "attachment");
response.setContentType("text/csv; charset=windows-1252");
writer = new OutputStreamWriter(os, Util.WINDOWS1252);
writer.write("\u0000"); // flush() will be effective only if there is something in the buffer, this works with firefox, download dialog opens, but with not with IE
writer.flush(); // forces to open the download popup instantly
fooManager.processCSV(some params..., writer); // generated on the fly and written in writer direclty
} catch (IOException e) {
logger.debug("csv: IOException ", e);
} finally {
if (writer != null) {
try {
writer.close(); // now IE will finally open download dialog...
} catch (IOException e) {
// ignore
}
}
}
謝謝!
1>驗證的提琴手您的迴應實際上是流式傳輸。 2>考慮使用僞造MIME類型(例如應用程序/強制下載)以避免來自安裝在機器上的任何Excel MIME過濾器的干擾。 – EricLaw
無法與IE一起使用。 Chrome,Firefox與其他MIME類型正常工作。我嘗試設置response.setContentLength(someRandomLenght),IE立即打開下載。看來IE需要一個文件大小來顯示對話框,否則它只會在文件下載後顯示。問題是,csv是動態生成的,所以我無法獲得文件長度。 (我正在運行Tomcat 7.0.42 btw) – Matt