js中文乱码
1.js页面代码
encodeURIComponent(fileName)
//下载批量导入模板
$("#downloadFile").on('click',function () {
var fileName="派单规则批量上传模板.xlsx";
//防止-中文乱码
fileName = encodeURIComponent(fileName);
//fileName = encodeURI(fileName)
var url=commonAddress()+"/download/template?fileName="+fileName;
window.location.href=url;
});
2.后端控制台–获取
filename = java.net.URLEncoder.encode(filename, “UTF-8”);
// 非IE浏览器的处理:
filename = new String(filename.getBytes(“UTF-8”), “ISO-8859-1”);
private static final String FIXED_PATH = "static/excel/";
private static final String USER_AGENT_MSIE = "MSIE";
private static final String USER_AGENT_TRIDENT = "Trident";
@RequestMapping("/template")
@ResponseBody
public void downloadTemplate(@RequestParam Map<String,String> params, HttpServletResponse response, HttpServletRequest request)throws IOException {
log.debug("DownloadController{}==>downloadTemplate()");
InputStream inputStream = null;
OutputStream os = null;
try{
String path = Thread.currentThread().getContextClassLoader()
.getResource("").getPath()+FIXED_PATH+params.get("fileName");
inputStream = new FileInputStream(new File(path));
//假如以中文名下载的话,设置下载文件名称
String filename = params.get("fileName");
// 针对IE或者以IE为内核的浏览器:
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains(USER_AGENT_MSIE) || userAgent.contains(USER_AGENT_TRIDENT)) {
filename = java.net.URLEncoder.encode(filename, "UTF-8");
} else {
// 非IE浏览器的处理:
filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
//设置文件下载头
response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", filename));
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
response.setCharacterEncoding("UTF-8");
os = response.getOutputStream();
byte[] b = new byte[2048];
int len;
while((len = inputStream .read(b)) > 0){
os.write(b, 0, len);
}
}catch (Exception e){
log.error(e.getMessage());
} finally {
if(os != null) {
try {
os.close();
} catch (Exception e) {
log.error(e.getMessage());
}
}
if(inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
}