作者stw82 (Godhand)
看板java
标题[问题] 动态取得图档时 参数编码问题
时间Mon Sep 21 11:14:50 2015
使用的框架是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://webptt.com/cn.aspx?n=bbs/java/M.1442805294.A.C25.html
1F:推 kojilin: 我没记错http get 不会走 setCharacterEncoding. 09/21 14:00
2F:→ kojilin: tomcat 就有 URIEncoding 的设定。 09/21 14:03
3F:→ stw82: 下午试了一下 要encode两次以後 在後端用URLDecoder 09/21 15:14
4F:→ stw82: 才能取得正确的值 09/21 15:14
5F:推 Dnight: 你的中文档名编码确定不是big5是UTF-8吗? 09/21 18:25
6F:推 PttTime: server.xml Connector useBodyEncodingForURI="true" 09/21 21:36
7F:推 jay80915: 用get取得参数需要在转一次,String newPath = new Strin 09/21 23:15
8F:→ jay80915: g(path.getBytes("ISO-8859-1"), "UTF-8"); 09/21 23:15