Java:讀取下載文檔

        public void doPost(HttpServletRequest request, HttpServletResponse response)  
                throws ServletException, IOException {  
            String file = request.getParameter("file");
            //處理請求  
            //讀取要下載的文件  
            File f = new File("Book1.xls"); 
            String path=request.getSession().getServletContext().getRealPath("");
            path =path.replace("\\", "/")+"/"+file;
            f = new File(path);  
            if(f.exists()){  
                FileInputStream  fis = new FileInputStream(f);  
                String filename=URLEncoder.encode(f.getName(),"utf-8"); //解決中文文件名下載後亂碼的問題  
                byte[] b = new byte[fis.available()];  
                fis.read(b);  
                response.setCharacterEncoding("utf-8");  
                response.setHeader("Content-Disposition","attachment; filename="+filename+"");  
                //獲取響應報文輸出流對象  
                ServletOutputStream  out =response.getOutputStream();  
                //輸出  
                out.write(b);  
                out.flush();  
                out.close();  
            }     
              
        }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章