Struts2 stream 結果類型下載文件時,文件名中文亂碼、內容亂碼。Action 代碼:
public InputStream getInputStream() throws Exception {
this.fileName = d.getDatumname();
ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "utf-8"));
return ServletActionContext.getServletContext().getResourceAsStream("upload//" + fileName);
}
struts.xml 配置:
<result name="success" type="stream">
<param name="contentType">application/octet-stream;charset=iso8859-1</param>
<param name="inputName">inputStream</param>
<param name="bufferSize">4096</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
</result>
conf/server.xml,Connector 添加 URIEncoding="UTF-8",保證 URL 參數解碼正確。
<Connector port="8080" protocol="HTTP/1.1" URIEncoding="UTF-8" ... />
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
var fileName = "中文文件.pdf";
fileName = encodeURIComponent(encodeURIComponent(fileName)); // 雙重編碼
window.location.href = "download.action?fileName=" + fileName;
contentType 設置為 application/octet-stream;charset=UTF-8。contentDisposition 使用 filename*=UTF-8''${encodedFileName} (RFC 5987) 現代瀏覽器兼容更好,需在 Action 中預編碼 encodedFileName。fileName getter 返回已編碼字符串,或由 Struts2 自動調用 URLEncoder(需配置 struts.i18n.encoding=UTF-8)。若文件內容亦亂碼,檢查:
InputStreamReader(stream, "UTF-8"))。cos.jar/commons-fileupload 需設置 setHeaderEncoding("UTF-8"))。系統性統一三層編碼,可徹底解決 Struts2 文件下載中文亂碼問題。