*****为服务器的编码方式
1.MultipartFile上传文件
目的路径需要按照服务器的地址进行编码:
filename = new String( filename .getBytes("utf-8") , "*****");
FileUtils.copyInputStreamToFile(myfile.getInputStream(),
new File(destPath, filename));
2.下载文件
文件存放路径需要按照服务器的地址进行编码:
filePath = new String(filePath.getBytes("utf-8"), "*****");
下载时:
response.setContentType("application/octet-stream;charset=utf-8");
//filename为下载文件的中文名字
String tempStr = new String(filename.getBytes("utf-8"), "*****");
response.addHeader("Content-Disposition","attachment;filename=" + new String(tempStr.getBytes("*****"),"iso-8859-1"));
OutputStream outp = null;
FileInputStream in = null;
try{
in = new FileInputStream(filePath);
outp = response.getOutputStream();
byte[] b = new byte[1024];
int i = 0;
while((i = in.read(b)) > 0){
outp.write(b, 0, i);
}
outp.flush();
outp.close();
outp=null;
response.flushBuffer();
logger.info("no error " );
}catch(FileNotFoundException e){
System.out.println("Error!!");
logger.info("FileNotFoundException e: " + e);
e.printStackTrace();
session.setAttribute("fileDownload", 0);
}
finally{
if(in != null){
in.close();
in = null;
}
if(outp != null){
outp.close();
outp = null;
}
}
}
3.从js向后台传递中文参数
JSP的JS中:中文参数用encodeURI(encodeURI(中文参数)),经过两次转码。例如:
function show(next,id,realName){
document.forms['f2'].action="usersearchNextPage?next="+next+"&id="+id+"&realName="+encodeURI(encodeURI(realName));
document.forms['f2'].submit();
}
其中 realName是中文参数。故在提交的URL中将realName转码两次。encodeURI(encodeURI(realName))
Action中:接收中文参数时解码。用:java.net.URLDecoder.decode(realName,"UTF-8");
如:
String realName = ServletActionContext.getRequest().getParameter("realName");
try {
realName = java.net.URLDecoder.decode(realName,"UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}