jsp檔案下載方法
來源:互聯網
上載者:User
<%
response.setContentType(fileminitype);
response.setHeader("Location",filename);
response.setHeader("Cache-Control", "max-age=" + cacheTime);
response.setHeader("Content-Disposition", "attachment; filename=" + filename); //filename應該是編碼後的(utf-8)
response.setContentLength(filelength);
OutputStream outputStream = response.getOutputStream();
InputStream inputStream = new FileInputStream(filepath);
byte[] buffer = new byte[1024];
int i = -1;
while ((i = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, i);
}
outputStream.flush();
outputStream.close();
inputStream.close();
outputStream = null;
%>
3。既然是JSP的話,還有一種方式就是用Applet來實現檔案的下載。不過客戶首先得信任你的這個Applet小程式,由這個程式來接受由servlet發送來的資料流,並寫入到本地。
servlet端樣本
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType(" text/plain ");
OutputStream outputStream = null;
try {
outputStream = res.getOutputStream();
popFile(srcFile, outputStream)) ;//把檔案路徑為srcFile的檔案寫入到outputStream中。
} catch (IOException e) {
e.printStackTrace();
}
}
JApplet端樣本
URLConnection con;
try {
con = url.openConnection();//url是被調用的SERVLET的網址 如http://localhost:8080/sendDateSevlet.do
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-Type",
"application/octet-stream");
InputStream in = con.getInputStream();
ProgressMonitorInputStream pmInputStream = new ProgressMonitorInputStream(
pane, "正在從伺服器下載檔案內容", in);
ProgressMonitor pMonitor = pmInputStream
.getProgressMonitor();
pMonitor.setMillisToDecideToPopup(3);
pMonitor.setMillisToPopup(3);
String localfilepath = localstr + filename ;//localfilepath本地路徑,localstr檔案檔案夾,filename本地檔案名稱
if(saveFilsaveFilee(localfilepath,pmInputStream)){ //方法saveFilsaveFilee是把輸入資料流pmInputStream寫到檔案localfilepath中。
openLocalFile(localfilepath);
}
4。順便把JApplet上傳檔案的代碼也貼上來.
JApplet端樣本
URLConnection con;
try {
con = url.openConnection();//url是被調用的SERVLET的網址 如http://localhost:8080/sendDateSevlet.do
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-Type",
"application/octet-stream");
OutputStream out = con.getOutputStream();
String localfilepath = localstr + filename; //localfilepath本地路徑,localstr檔案檔案夾,filename本地檔案名稱
getOutputStream(localfilepath,out);//檔案getOutputStream是把檔案localfilepath寫到輸出資料流out中。
InputStream in = con.getInputStream();
return true;
}catch (IOException e) {
System.out.println("檔案上傳出錯!");
e.printStackTrace();
}
servlet端程式碼範例
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType(" text/plain ");
InputStream inputStream = null;
try {
inputStream = res.getInputStream();
writefile(srcFile, inputStream);//把輸入資料流inputStream儲存到檔案路徑為srcFile的檔案中
} catch (IOException e) {
e.printStackTrace();
}
} // end service