在開發項目時遇到,在jsp 中通過 a 標簽的方式,訪問后臺servlet,調用 客戶端以下載的方式打開文件,遇到中文文件名亂碼,找不到問題,導致下載失敗問題,弄了很久才弄出點樣子,不是很科學,但暫時可用
大體思路:
1.文件夾中存放要下載的文件名為 英文文件名;
2.. 前臺jsp a標簽攜帶 路徑及文件名訪問后臺servlet,其中路徑中只有不含有中文,文件名可以為中文,訪問后臺servlet;
3. 后臺先取出文件路徑,和后臺準備的參數進行組裝拼接,得到不含中文的下載路徑,構建輸入流;
4. 因為我的tomcat中的 servlet.xml 中8080端口位置有設置 編碼,所以后臺直接取出含有中文的文件名,作為下載文件的文件名通知客戶端以下載的方式打開進行下載
servlet 中設置字符編碼
<Connector port="48080" PRotocol="HTTP/1.1" connectionTimeout="20000" redirectPort="38443" URIEncoding="ISO-8859-1"/>jsp頁面中 通過 a 標簽攜帶信息訪問后臺servlet
<a href='servlet/DownLoadFileSvl?path=文件相對路徑&fileName=文件名'>下載</a>后臺servlet get請求
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getParameter("path");// get方式提交的 path = new String(path.getBytes("ISO-8859-1"), "UTF-8");// 前臺傳上來的文件相對路徑 log.debug("前臺傳上來的文件相對路徑: " + path); String path1 = this.getServletContext().getRealPath("") .replace(request.getContextPath() + "/", ""); log.debug("/t/n--獲取的文件夾名稱:" + path1); String upLoad = path1 + "/file/" + path; //組裝下載路徑 upLoad = new String(upLoad.getBytes(), "utf-8"); // 構建輸入流 InputStream in = new FileInputStream(upLoad); // 下載 response.setCharacterEncoding("utf-8"); log.debug("/n/t下載的文件名: " + request.getParameter("fileName")); // 通知客戶端以下載的方式打開 response.setHeader("Content-Disposition", "attachment;filename=" + request.getParameter("fileName")); OutputStream out = response.getOutputStream(); int len = -1; byte b[] = new byte[1024]; while ((len = in.read(b)) != -1) { out.write(b, 0, len); } in.close(); out.close(); }以上就是今天的想法,沒有好好整理過的,后期有時間再進行整理。
新聞熱點
疑難解答