jsp中實現文件下載的最簡單的方式是在網頁上做超級鏈接,如:<a href="music/abc.mp3">點擊下載</a>。但是這樣服務器上的目錄資源會直接暴露給最終用戶,會給網站帶來一些不安全的因素。因此可以采用其它方式實現下載,可以采用:1、RequestDispatcher的方式進行;2、采用文件流輸出的方式下載。
1、采用RequestDispatcher的方式進行
jsp頁面中添加如下代碼:
<%
response.setContentType("application/x-download");//設置為下載application/x-download
String filedownload = "/要下載的文件名";//即將下載的文件的相對路徑
String filedisplay = "最終要顯示給用戶的保存文件名";//下載文件時顯示的文件保存名稱
filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);
try
{
RequestDispatcher dis = application.getRequestDispatcher(filedownload);
if(dis!= null)
{
dis.forward(request,response);
}
response.flushBuffer();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
}
%>
2、采用文件流輸出的方式下載
<%@page language="java" contentType="application/x-msdownload" pageEncoding="gb2312"%><%
//關于文件下載時采用文件流輸出的方式處理:
//加上response.reset(),并且所有的%>后面不要換行,包括最后一個;
response.reset();//可以加也可以不加
response.setContentType("application/x-download");
String filedownload = "想辦法找到要提供下載的文件的物理路徑+文件名";
String filedisplay = "給用戶提供的下載文件名";
filedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);
OutputStream outp = null;
FileInputStream in = null;
try
{
outp = response.getOutputStream();
in = new FileInputStream(filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while((i = in.read(b)) > 0)
{
outp.write(b, 0, i);
}
outp.flush();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(in != null)
{
in.close();
in = null;
}
if(outp != null)
{
outp.close();
outp = null;
}
}
%>
在wsad里面寫JSP文件下載,總是出現這個異常,getOutputStream() has already been called for this response,輸出流已經被調用了.
上網查半天終于明白一點,JSP早下載文件的時候用到了OutputStream,而在Application Server在處理編譯jsp時對于%>和<%之間的內容一般是原樣輸出,而且默認是PrintWriter.
posted on 2008-01-17 17:10
SIMONE 閱讀(34445)
評論(7) 編輯 收藏 所屬分類:
JAVA 、
JSP