2013-09-25 29 views
0

使用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 
    } 
    } 
} 

謝謝!

+0

1>驗證的提琴手您的迴應實際上是流式傳輸。 2>考慮使用僞造MIME類型(例如應用程序/強制下載)以避免來自安裝在機器上的任何Excel MIME過濾器的干擾。 – EricLaw

+0

無法與IE一起使用。 Chrome,Firefox與其他MIME類型正常工作。我嘗試設置response.setContentLength(someRandomLenght),IE立即打開下載。看來IE需要一個文件大小來顯示對話框,否則它只會在文件下載後顯示。問題是,csv是動態生成的,所以我無法獲得文件長度。 (我正在運行Tomcat 7.0.42 btw) – Matt

回答

0

也許你需要的文件名:

Content-Disposition: attachment; filename=FILENAME 

而且,強行打開另存爲對話框中,添加:

Content-Type: application/force-download 

或者:

Content-Type: application/octet-stream 
+0

我嘗試了一個文件名,它不工作。否則,如果沒有文件名,文件名將從下載URL中獲取。 – Matt

+0

你說得對。該名稱就像最後一個斜槓後的網址。根據瀏覽器的不同,這會嘗試自動打開文件。在這種情況下,您應該發送一個通用MIME來避免這種情況,就像Google Chrome中的mp3一樣。 –

相關問題