:(W11DownLoadServlet.java和downlist.jsp和Downservlet.java)中介紹
1) ?DownLoadServlet.java中有關(guān)遍歷本地的資源,以及要轉(zhuǎn)發(fā)到downlist.jsp中展示,DownServlet.java中進(jìn)行下載代碼的實(shí)現(xiàn)
1.1)DownLoadServlet.java中有關(guān)遍歷本地的資源:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub//response.getWriter().append("Served at: ").append(request.getContextPath());//保存文件的完整名稱(key)和簡(jiǎn)化名稱(value)MapfileNames = new HashMap<>();
//獲取目錄中所有文件
String path = "D:/upload";
File dirFile = new File(path);
//沒有判斷文件夾的情況。
if (dirFile!=null||dirFile.isDirectory()) {
String[] list = dirFile.list();
if (list!=null&&list.length>0) {
for (int i = 0; i < list.length; i++) {
String fullName = list[i];
String shortName = fullName.substring(fullName.indexOf("-")+1);
fileNames.put(fullName, shortName);
}
}
}
request.setAttribute("fileMap", fileNames);
//通過轉(zhuǎn)發(fā)調(diào)到界面
request.getRequestDispatcher("/downlist.jsp").forward(request, response);
}
1.2)轉(zhuǎn)發(fā)到downlist.jsp中展示
1.3)DownServlet.java中進(jìn)行下載代碼的實(shí)現(xiàn)
:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
String fileName = request.getParameter("name");
//處理get方式的中文亂碼
fileName = new String(fileName.getBytes("iso-8859-1"),"utf8");
String path = "D:/upload";
//獲取輸入流
InputStream in = new FileInputStream(new File(path,fileName));
//對(duì)URL的處理,不處理文件名中 中文會(huì)變成“ ”等形式
fileName=URLEncoder.encode(fileName,"utf8");
//設(shè)置下載的響應(yīng)頭,請(qǐng)求的內(nèi)容存為文件時(shí),需要一個(gè)默認(rèn)的文件名
response.setHeader("content-disposition", "attachment;fileName="+fileName);
//獲得響應(yīng)的輸出流
ServletOutputStream out = response.getOutputStream();
//將輸入流中的數(shù)據(jù)通過輸出流進(jìn)行保存
byte[] buff = new byte[1024];
int len=-1;
while ((len=in.read(buff))!=-1) {
out.write(buff,0,len);
}
out.close();
in.close();
}
注:********
//獲取輸入流
InputStream in = new FileInputStream(new File(path,fileName));
//對(duì)URL的處理,不處理文件名中 中文會(huì)變成“ ”等形式
fileName=URLEncoder.encode(fileName,"utf8");
//設(shè)置下載的響應(yīng)頭,請(qǐng)求的內(nèi)容存為文件時(shí),需要一個(gè)默認(rèn)的文件名
response.setHeader("content-disposition", "attachment;fileName="+fileName);
//獲得響應(yīng)的輸出流
ServletOutputStream out = response.getOutputStream();