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");
OutputStream outp = null;
FileInputStream in = null;
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();
System.out.println("Error!");
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.