程式如下:
<%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*" pageEncoding="gb2312"%>
<%
//關于檔案下載下傳時采用檔案流輸出的方式處理:
//加上response.reset(),并且所有的%>後面不要換行,包括最後一個;
//因為Application Server在處理編譯jsp時對于%>和<%之間的内容一般是原樣輸出,而且預設是PrintWriter,
//而你卻要進行流輸出:ServletOutputStream,這樣做相當于試圖在Servlet中使用兩種輸出機制,
//就會發生:getOutputStream() has already been called for this response的錯誤
//詳細請見《More Java Pitfill》一書的第二部分 Web層Item 33:試圖在Servlet中使用兩種輸出機制 270
//而且如果有換行,對于文本檔案沒有什麼問題,但是對于其它格式,比如AutoCAD、Word、Excel等檔案
//下載下傳下來的檔案中就會多出一些換行符0x0d和0x0a,這樣可能導緻某些格式的檔案無法打開,有些也可以正常打開。
response.reset();//可以加也可以不加
response.setContentType("application/x-download");//設定為下載下傳application/x-download
// /../../退WEB-INF/classes兩級到應用的根目錄下去,注意Tomcat與WebLogic下面這一句得到的路徑不同,WebLogic中路徑最後沒有/
System.out.println(this.getClass().getClassLoader().getResource("/").getPath());
String filenamedownload = this.getClass().getClassLoader().getResource("/").getPath() + "/../../系統解決方案.doc";
String filenamedisplay = "系統解決方案.doc";//系統解決方案.txt
filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while((i = fis.read(b)) > 0)
{
output.write(b, 0, i);
}
output.flush();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
fis = null;
}
if(output != null)
{
output.close();
output = null;
}
}
%>