使用 SmartUpload 下載文件時,若通過 Ajax 獲取,可能出現中文內容顯示異常的問題。以下是服務端與客戶端的關鍵代碼。
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("GBK");
SmartUpload su = new SmartUpload();
su.initialize(this.getServletConfig(), req, resp);
// 設定 contentDisposition 為 null,禁止浏覽器自動打開文件,
// 保證點擊鏈接後是「下載」而非直接打開(如 .doc/.pdf 會被相應軟件打開)
su.setContentDisposition(null);
try {
su.downloadFile("D://upload/" + "test.txt");
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
<script>
function getFile(){
$.get("<%=basePath%>LoadFileServlet", "", function(data){
alert(data);
});
}
</script>
<a href="#" onclick="getFile()">getfile</a>
現象:通過 Ajax 獲取時 txt 中的中文不顯示,而直接用超鏈接訪問服務端下載則無亂碼。這通常與響應編碼設置有關,可嘗試在輸出前統一設置 setContentType 與字符編碼,確保前後端一致。