javamail附件中文乱码:
/*
@从BodyPart中提取使用ISO-8859-1编吗的文件名
@因为BodyPart.getFilename()过程已经对文件名作了一次编码,有时不能直接使用
*/
public static String getISOFileName(Part body){
//设置一个标志,判断文件名从Content-Disposition中获取还是从Content-Type中获取
boolean flag=true;
if(body==null){
return null;
}
String[] cdis;
try{
cdis=body.getHeader("Content-Disposition");
}
catch(Exception e){
return null;
}
if(cdis==null){
flag=false;
}
if(!flag){
try{
cdis=body.getHeader("Content-Type");
}
catch(Exception e){
return null;
}
}
if(cdis==null){
return null;
}
if(cdis[0]==null){
return null;
}
//从Content-Disposition中获取文件名
if(flag){
int pos=cdis[0].indexOf("filename=");
if(pos<0){
return null;
}
//如果文件名带引号
if(cdis[0].charAt(cdis[0].length()-1)=='"'){
return cdis[0].substring(pos+10,cdis[0].length()-1);
}
return cdis[0].substring(pos+9,cdis[0].length());
}
else{
int pos=cdis[0].indexOf("name=");
if(pos<0){
return null;
}
//如果文件名带引号
if(cdis[0].charAt(cdis[0].length()-1)=='"'){
return cdis[0].substring(pos+6,cdis[0].length()-1);
}
return cdis[0].substring(pos+5,cdis[0].length());
}
}
/*
@从BodyPart中提取使用ISO-8859-1编吗的文件名
@因为BodyPart.getFilename()过程已经对文件名作了一次编码,有时不能直接使用
*/
public static String getISOFileName(Part body){
//设置一个标志,判断文件名从Content-Disposition中获取还是从Content-Type中获取
boolean flag=true;
if(body==null){
return null;
}
String[] cdis;
try{
cdis=body.getHeader("Content-Disposition");
}
catch(Exception e){
return null;
}
if(cdis==null){
flag=false;
}
if(!flag){
try{
cdis=body.getHeader("Content-Type");
}
catch(Exception e){
return null;
}
}
if(cdis==null){
return null;
}
if(cdis[0]==null){
return null;
}
//从Content-Disposition中获取文件名
if(flag){
int pos=cdis[0].indexOf("filename=");
if(pos<0){
return null;
}
//如果文件名带引号
if(cdis[0].charAt(cdis[0].length()-1)=='"'){
return cdis[0].substring(pos+10,cdis[0].length()-1);
}
return cdis[0].substring(pos+9,cdis[0].length());
}
else{
int pos=cdis[0].indexOf("name=");
if(pos<0){
return null;
}
//如果文件名带引号
if(cdis[0].charAt(cdis[0].length()-1)=='"'){
return cdis[0].substring(pos+6,cdis[0].length()-1);
}
return cdis[0].substring(pos+5,cdis[0].length());
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货