看板 java 關於我們 聯絡資訊
使用的框架是Spring MVC, 由於必須從非context path下的特定路徑 取得圖檔顯示在畫面上, 寫了一個如文末附的method 在頁面上 img的src指向controller後 透過傳入實際路徑來取得圖檔並扔給ServletOutputStream 目前的狀況是 檔案名稱只包含英文跟數字的話沒有問題 但只要含有中文時 request.getParameter("path")取得的變數就會有亂碼 有試過request.setCharacterEncoding("UTF-8"); (其實有先print過request.getCharacterEncoding(), 已經是UTF-8) 也試過把${imgPath}給encode後 後端controller用 URLDecoder.decode(request.getParameter("path"),"UTF-8") 但無論怎試 出來的依然還是亂碼 不知道是否有人碰過類似的問題? 該如何去設定encoding才能取得正確的包含中文的檔名路徑? <img src="./myController?method=getImage&path=${imgPath}"/> @RequestMapping(params = "method=getImage") public void getImage(HttpServletResponse response ,HttpServletRequest request) throws IOException{ String mimeType = context.getMimeType(request.getParameter("path")); response.setContentType((mimeType != null) ? mimeType : "application/octet-stream"); ServletOutputStream out = response.getOutputStream(); InputStream in = new FileInputStream(request.getParameter("path")); IOUtils.copy(in, out); in.close(); out.close(); } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.250.69.174 ※ 文章網址: https://www.ptt.cc/bbs/java/M.1442805294.A.C25.html
kojilin: 我沒記錯http get 不會走 setCharacterEncoding. 09/21 14:00
kojilin: tomcat 就有 URIEncoding 的設定。 09/21 14:03
stw82: 下午試了一下 要encode兩次以後 在後端用URLDecoder 09/21 15:14
stw82: 才能取得正確的值 09/21 15:14
Dnight: 你的中文檔名編碼確定不是big5是UTF-8嗎? 09/21 18:25
PttTime: server.xml Connector useBodyEncodingForURI="true" 09/21 21:36
jay80915: 用get取得參數需要在轉一次,String newPath = new Strin 09/21 23:15
jay80915: g(path.getBytes("ISO-8859-1"), "UTF-8"); 09/21 23:15