如下方法处理中文附件名:
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());
}
}
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());
}
}
解决方案 »
- java-记事本程序 求大神修改,小弟弄了好久都不行
- 求过路朋友给个java括号嵌套的正则表达式
- Java的反射机制!!Java高手请进!
- 关于利用java将txt文件转换为pdf格式的问题
- 急,怎样判断复选框是否是选中状态,在线等给分
- 在一个普通的java class中如何运行ie?(假设本地机上有ie浏览器)
- 为什么我每次用UpdateUI刷新JTree时都有错?
- 一个好简单的问题---URL到底是什么?请详细解释一下
- 请问各位大虾,不用javaMail如何才能发送附件。
- 给JFrame加背景图片之后,怎么菜单栏看不见了,鼠标放上去,可以选择!
- 急,在线等待!RMI绑定服务端抛出异常............
- 如何从java控制台获得用户输入?
还是MimeBodyPart mbp2=new MimeBodyPart();中的mbp2
获取的新文件名应该mbp2.setFileName(filename);吗?