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

作者: stw82 (Godhand)   2015-09-21 11:14:50
使用的框架是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();
}
作者: kojilin (阿~~小達達)   2015-09-21 14:00:00
我沒記錯http get 不會走 setCharacterEncoding.tomcat 就有 URIEncoding 的設定。
作者: stw82 (Godhand)   2015-09-21 15:14:00
下午試了一下 要encode兩次以後 在後端用URLDecoder才能取得正確的值
作者: Dnight (暗夜)   2015-09-21 18:25:00
你的中文檔名編碼確定不是big5是UTF-8嗎?
作者: PttTime   2015-09-21 21:36:00
server.xml Connector useBodyEncodingForURI="true"
作者: jay80915 (一種感覺)   2015-09-21 23:15:00
用get取得參數需要在轉一次,String newPath = new String(path.getBytes("ISO-8859-1"), "UTF-8");

Links booklink

Contact Us: admin [ a t ] ucptt.com