創建web工程,使用response實現文件的下載.
在webRoot下創建download文件,里面包含要下載的文件,現在把源碼貼上來,然后再說我遇到的問題
1 public class DownLoadDemo extends HttpServlet { 2 3 public void doGet(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 6 String path = this.getServletContext().getRealPath("/download/倒影.jpg"); 7 System.out.println("路徑是==="+path); 8 //lastIndexOf返回的是最后一次出現的索引,截取的話必須要+1,從/的后面開始截取 9 String filename = path.substring(path.lastIndexOf("/")+1); 10 //注意:在mac中就是/,但是在windows中,文件路徑是\,\是轉譯符,要再加上一個\,\\才是\: 11 // String filename = path.substring(path.lastIndexOf("\\")+1);這是在windows下的文件路徑截取 12 System.out.println("文件名是==="+filename); 13 14 //如果下載的文件是中文的話,文件需要經過URL編碼 15 response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8")); 16 InputStream in = null; 17 OutputStream out = null; 18 try { 19 in = new FileInputStream(path); 20 int len = 0; 21 byte bys[] = new byte[1024]; 22 out = response.getOutputStream(); 23 while((len = in.read(bys)) > 0){ 24 out.write(bys, 0, len); 25 } 26 } finally { 27 if (in != null) { 28 try { 29 in.close(); 30 } catch (Exception e) { 31 e.printStackTrace(); 32 } 33 } 34 } 35 36 }
兩個需要注意的點:
1.通過文件路徑獲取文件名,在代碼中已經說過,windows和mac的路徑是不一樣的,這個一定要注意,不然下載就會出錯
2.當文件名是中文時,文件要通過URL編碼