2012-08-02 150 views
4

我想從富表數據表中導出數據我已經從數據表中的數據創建了outputStream。現在要發送這個OutputStream到瀏覽器並讓它保存。我怎樣才能做到這一點?發送OutputStream到瀏覽器並讓瀏覽器保存它

FileOutputStream stream = new FileOutputStream(new File(PATH));

OutputStream out = myMthodToCreateOutPutStream();

現在該怎麼保存這個out到瀏覽器。

回答

12

目前還不清楚您在哪裏閱讀您的數據。您需要創建一個InputStream來讀取數據。

然後,您首先需要將響應頭設置爲

HttpServletResponse.setHeader("Content-Disposition", "attachment; filename=datafile.xls"); 

使用任何你需要的文件名。

然後設置MIME類型:

response.setContentType("application/vnd.ms-excel"); 

使用MIME類型,你需要。

這時需要使用響應對象來獲取它的OutputStream -

OutputStream outStream = response.getOutputStream(); 

現在寫它:

byte[] buf = new byte[4096]; 
int len = -1; 

//Write the file contents to the servlet response 
//Using a buffer of 4kb (configurable). This can be 
//optimized based on web server and app server 
//properties 
while ((len = inStream.read(buf)) != -1) { 
    outStream.write(buf, 0, len); 
} 

outStream.flush(); 
outStream.close(); 
+0

這個答案給了我一個提示,以解決我的問題..非常感謝 – 2012-08-05 08:51:01