天天看點

java 檔案下載下傳,中文表名,中文内容

@RequestMapping("userDownloadTemplet")
	private void userDownloadTemplet(HttpServletRequest request,HttpServletResponse response, String filePath){ 
        try {
            
        	filePath = request.getSession().getServletContext().getRealPath("/WEB-INF/download_templet/使用者資訊模闆.csv");
            File file = new File(filePath);
            String filename = file.getName(); // 取得檔案名。
//            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase(); // 得檔案的字尾名。
            InputStream fis = new BufferedInputStream(new FileInputStream(filePath)); // 以流的形式下載下傳檔案。
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset(); // 清空response
            filename = new String(filename.getBytes("GBK"), "ISO-8859-1");;
			response.setHeader("Content-Disposition","attachment;filename=" + filename);
			response.setContentType("application/vnd.ms-excel;");  //設定檔案類型  
            response.setCharacterEncoding("utf-8");  
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);// 設定response的Header
            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();
        }
    }           

複制