Struts2 XML 配置下載動作時,中文檔名在瀏覽器顯示為亂碼,需對 Content-Disposition 標頭中的 filename 進行正確編碼。
在 Action 中重寫 getContentDisposition() 或攔截器設定標頭:
String fileName = "中文檔名.pdf";
String encodedName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedName);
若使用 stream Result Type,可在 struts.xml 設定:
<result type="stream">
<param name="contentDisposition">attachment; filename*=UTF-8''${encodedFileName}</param>
<param name="inputName">inputStream</param>
</result>
Action 需提供 getEncodedFileName() 返回已編碼字串。
同時提供 filename (ISO-8859-1) 與 filename* (UTF-8) 兩種格式:
response.setHeader("Content-Disposition",
"attachment; filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + "\"; " +
"filename*=UTF-8''" + encodedName);