第一種下載方式:
此方式 下載,在服務器上必須有文件 的存在
用java 程序 從服務器 上下載文件到 本地電腦上
和上傳不一樣的是,下載是從服務器上的文件複製到本地電腦上
那麼,服務器必須 是輸出者 ,本地就是接收者
服務器端的輸出,只能是response 對象 , 本地接收對象 就是File ,從response 到 File 之間 需要一座橋樑,那麼這座橋樑就是 io ----------流
1、用到 response 對象從服務器端輸出此文件
2、用File 創建對象
3、用字節/字符流 進行輸送
public boolean download(HttpServletResponse response,
ActionContext context) {
boolean flag = true;
try {
String filePath2 = context.getRequest().getRealPath("/"); //取當前系統路徑
// path是指欲下載的文件的路徑。在path 路徑下創建名爲
File file = new File(filePath2 + "zjh/" + "下載.xls"
if (!file.exists()){
flag = false;
}
// 取得文件名。
String filename = file.getName();
// 取得文件的後綴名。
String ext = filename.substring(filename.lastIndexOf(".") + 1)
.toUpperCase();
// 以流的形式下載文件。
InputStream fis = new BufferedInputStream(new FileInputStream(
filePath2 + "zjh/" + "下載.xls"
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
response.addHeader("Content-Disposition", "attachment;filename="+ java.net.URLEncoder.encode("下載.xsl","utf-8"));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
flag = false;
}
// return response;
return flag;
}
注:服務器上必須要有當前被下載的文件,才能運用此方法下載