[問題] 動態取得圖檔時 參數編碼問題

看板java作者 (Godhand)時間9年前 (2015/09/21 11:14), 編輯推噓4(404)
留言8則, 5人參與, 最新討論串1/1
使用的框架是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

09/21 14:00, , 1F
我沒記錯http get 不會走 setCharacterEncoding.
09/21 14:00, 1F

09/21 14:03, , 2F
tomcat 就有 URIEncoding 的設定。
09/21 14:03, 2F

09/21 15:14, , 3F
下午試了一下 要encode兩次以後 在後端用URLDecoder
09/21 15:14, 3F

09/21 15:14, , 4F
才能取得正確的值
09/21 15:14, 4F

09/21 18:25, , 5F
你的中文檔名編碼確定不是big5是UTF-8嗎?
09/21 18:25, 5F

09/21 21:36, , 6F
server.xml Connector useBodyEncodingForURI="true"
09/21 21:36, 6F

09/21 23:15, , 7F
用get取得參數需要在轉一次,String newPath = new Strin
09/21 23:15, 7F

09/21 23:15, , 8F
g(path.getBytes("ISO-8859-1"), "UTF-8");
09/21 23:15, 8F
文章代碼(AID): #1L_tOkmb (java)
文章代碼(AID): #1L_tOkmb (java)