小新 的 BLOG
            
            -=java、Web编程=-

一下午就写两个函数-就为了附件中文名

1、设置文件名:
            BASE64Encoder bASE64Encoder = new BASE64Encoder();
            fileBodyPart.setFileName("=?GBK?B?"
                    + bASE64Encoder.encode((fileDataSource.getName()).getBytes()) + "=?=");        

2、
    /**
     * 保存附件文件
     * @param fileNameHead 路径+附件开头
     * @param fileNameContent 文件名
     * @param inputStream part.getInputStream()
     */
    private static void saveFile(String fileNameHead,String fileNameContent,InputStream inputStream){
        try{    
            fileNameContent = convertGBEncoding(fileNameContent);
            fileNameContent = MimeUtility.decodeText(fileNameContent);
            String filename = fileNameHead + "_0_" + fileNameContent;
            File file = new File(filename);            
            for (int i=0; file.exists(); i++) {
                filename = fileNameHead + "_" + i + "_" + fileNameContent;
                file = new File(filename);        
            }            
            saveToDisk(filename,inputStream);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
3、
    /**
     * 中文编码转换
     * @param content
     * @return
     */
    private static String convertGBEncoding(String content) {
        boolean exist = false;
        int encodeStart = 0;
        if ((content.toUpperCase().startsWith("=?GB2312?B?") && content
                .toUpperCase().endsWith("=?="))){
            encodeStart = 11;
            exist = true;
        }
        if ( (content.toUpperCase().startsWith("=?GBK?B?") && content
                        .toUpperCase().endsWith("?="))) {
            encodeStart = 8;
            exist = true;
        }
        try {
            if (exist) {
                BASE64Decoder decoder = new BASE64Decoder();
                content = content.substring(encodeStart,content.indexOf("?=")-1);
                byte[] b = decoder.decodeBuffer(content);
                return new String(b);
            }else {
                return new String(content.getBytes("ISO-8859-1"), encodeing);
            }
        } catch (Exception ex) {
            return content;
        }
    }
标签集:TAGS:
回复Comments()点击Count()

回复Comments

{commenttime}{commentauthor}

{CommentUrl}
{commentcontent}
  用户登录
用户名
密 码
选 项:
 
  我的日历
  分类日志
  访问计数
  获取 RSS
bluelover 最新的 20 条日志
  最新评论
  友情链接
  联系我
                  GMail:bluelover@gmail.com
MSN:xini_huang@hotmail.com
QQ:85364603
Modified by blueloverPowered by 5DBlog.com