Khan's Notebook GCC/GNU/Linux Delphi/Window Java/Anywhere

路漫漫,长修远,我们不能没有钱
随笔 - 172, 文章 - 0, 评论 - 257, 引用 - 0
数据加载中……

java 上传文件代码,支持中文文件名和中文文件内容,可以同时提交多个参数

提交的表单代码:

< table  width ="100%"  border ="0"  cellspacing ="1"  cellpadding ="0"  bgcolor ="#FF9900"  align ="center" >
  
< form  ID =mainform   enctype ="multipart/form-data"  method ="post"  action ="file_Add.jsp?upload=true&parent_id=10" >
  
< tr  bgcolor ="#FFFFFF" >
    
< td  width ="15%"  height ="12" >< div  align ="center" ></ div ></ td >
    
< td  width ="15%"  height ="12" >
      
< div  align ="left" ></ div >
    
</ td >
    
< td  width ="15%"  height ="12" >   < div  align ="center" > 主编号: </ div ></ td >
    
< td  width ="15%"  height ="12" >
      
< div  align ="left" > 10 </ div >
    
</ td >
  
</ tr >

  
< tr  bgcolor ="#FFFFFF" >
    
< td  width ="15%"  height ="12" >< div  align ="center" > 文件路径: </ div ></ td >
    
< td  width ="15%"  height ="12" >
      
< div  align ="left" >< input  name ="filepath"  type ="text"  class ="smallInput"  id ="filepath"  size ="15"  value ="" ></ div >
    
</ td >
    
< td  width ="15%"  height ="12" >   < div  align ="center" > 文件类型: </ div ></ td >
    
< td  width ="15%"  height ="12" >
      
< div  align ="left" >
        
< select  name ="file_type" >
          
< option  selected > mid </ option >
          
< option > mmf </ option >
          
< option > arm </ option >
          
< option > midi </ option >
          
< option > mp3 </ option >
          
< option > 3gp </ option >
          
< option > gif </ option >
          
< option > jpg </ option >
          
< option > psd </ option >
        
</ select >
      
</ div >
    
</ td >
  
</ tr >

  
< tr  bgcolor ="#FFFFFF" >
    
< td  width ="15%"  height ="12" >< div  align ="center" > 和弦数: </ div ></ td >
    
< td  width ="15%"  height ="12" >
      
< div  align ="left" >
        
< select  name ="songstyle" >
          
< option  selected > 4 </ option >
          
< option > 16 </ option >
          
< option > 32 </ option >
          
< option > 40 </ option >
          
< option > 48 </ option >
          
< option > 60 </ option >
        
</ select >
      
</ div >
    
</ td >
    
< td  width ="15%"  height ="12" >   < div  align ="center" > 文件大小: </ div ></ td >
    
< td  width ="15%"  height ="12" >
      
< div  align ="left" >< input  name ="filesize"  type ="text"  class ="smallInput"  readonly ="readonly"  id ="filesize"  size ="15"  value ="27" ></ div >
    
</ td >
  
</ tr >
  
< tr  bgcolor ="#FFFFFF" >
    
< td  width ="15%"  height ="12" > 上传文件 </ td >
    
< td  width ="15%"  height ="12" >< div  align ="left" >< input  name ="fileupload"  type ="file"  class ="smallInput"  id ="fileupload"  size ="15" ></ div ></ td >
    
< td  width ="15%"  height ="12" >
      
< input  type ="submit"  name ="Submit"  value ="确定"  class ="smallInput" >
    
</ td >
    
< td  width ="15%"  height ="12" > &nbsp; </ td >
  
</ tr >
</ form >






文件上传的类:暂时只支持单个文件上传

package web.QiXiangTong;


import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
//import com.khan.net.*;


/*
  version 1.0
  修正了传递二进制文件不正常的问题, 因为我将流转成了字符串的方式解析, 导致二进制文件的不可见字符转码失败
  解决, 全部采用byte解析
  暂时还是只能上传单个文件
  支持传递文件的同时, 参数url参数
*/
public class uploadFile  {
    public static final int MAX_SIZE = 1024 * 1024*100;
    public static final String FILE_DIR = "d:/temp/";

    private int file_Size=0;
    private String file_Path = "";
    private HashMap hm = new HashMap();

    public String upLoad(HttpServletRequest req) {
        String tmpString ="";
        String result = "";
        DataInputStream dis = null;

        try {
            dis = new DataInputStream(req.getInputStream());
            String content = req.getContentType();
            if (content != null && content.indexOf("multipart/form-data") != -1) {

                int reqSize = req.getContentLength();
                byte[] data = new byte[reqSize];
               
                int bytesRead = 0;
                int totalBytesRead = 0;
                int sizeCheck = 0;
                while (totalBytesRead < reqSize) {
                    // check for maximum file size violation
                    sizeCheck = totalBytesRead + dis.available();
                    if (sizeCheck > MAX_SIZE)
                        result = "文件太大不能上传...";

                    bytesRead = dis.read(data, totalBytesRead, reqSize);
                    totalBytesRead += bytesRead;
                }

                tmpString = new String(data);
                hm = parseAnotherParam(tmpString);
//System.out.println("src datatmp |"+new String(data)+"|");
                int postion = arrayIndexOf(data, "\r\n".getBytes());
                byte[] split_arr = new byte[postion];
                System.arraycopy(data, 0, split_arr, 0, postion);
//System.out.println("split |"+new String(split_arr)+"|");

                postion = arrayIndexOf(data, "filename=\"".getBytes());
                byte[] dataTmp = new byte[data.length - postion];
                System.arraycopy(data, postion, dataTmp, 0, dataTmp.length);
                data = null;
                data = dataTmp.clone();


                String filePath =null;
                postion = arrayIndexOf(data, "Content-Type:".getBytes())-2;
                dataTmp = null;
                dataTmp = new byte[postion];
                System.arraycopy(data, 0, dataTmp, 0, dataTmp.length);
                filePath = new String(dataTmp);
                if (filePath==null && filePath.equals("")) return "";
//System.out.println("filename |"+filePath+"|");
               // 分离contentType 并赋值
                postion = arrayIndexOf(data, "Content-Type:".getBytes());
                dataTmp = null;
                dataTmp = new byte[data.length - postion];
                System.arraycopy(data, postion, dataTmp, 0, dataTmp.length);
                data = null;
                data = dataTmp.clone();
//System.out.println("src adatatmp |"+new String(data)+"|");
 
                postion = arrayIndexOf(data, "\n".getBytes()) + 1;
                dataTmp = null;
                dataTmp = new byte[data.length - postion];
                System.arraycopy(data, postion, dataTmp, 0, dataTmp.length);
                data = null;
                data = dataTmp.clone();
//System.out.println("datatmp |"+new String(data)+"|");

                // 分离文件信息 获得最终想要的字节
                postion = arrayIndexOf(data, split_arr);
                split_arr = null;
                dataTmp = null;
                dataTmp = new byte[postion - 2];
                System.arraycopy(data, 2, dataTmp, 0, dataTmp.length);
                data = null;
                data = dataTmp.clone();
//System.out.println("datatmp |"+new String(data)+"|");

                postion = arrayLastIndexOf(data, "\n".getBytes())-1;
                dataTmp = null;
                dataTmp = new byte[postion];
//System.out.println("postion:"+postion + " datalength:"+ data.length +" tmplength:" + dataTmp.length);
                System.arraycopy(data, 0, dataTmp, 0, dataTmp.length);

                data = null;
//System.out.println("data |"+new String(dataTmp)+"|");
                String file_path = getFileName(filePath);
//System.out.println("file_path:"+file_path);
                if(null != file_path) {
                  if (writeFile(dataTmp, FILE_DIR + file_path)) {
                    this.file_Size = dataTmp.length;
                    this.file_Path = FILE_DIR + file_path;
                    result = "文件上传完毕";
                  } else {
                    result = "文件上传失败";
                  }
                }else{
                    result = "文件名为空";
                }
                dataTmp = null;
            } else {
                result = "content 必须为 multipart/form-data";
            }
        } catch (UnsupportedEncodingException ex4) {
            result = "UnsupportedEncodingException错误";
        } catch (NullPointerException e) {
            result = "NullPointerException错误";
        } catch (IOException ex1) {
            result = "IOException 错误 ";
        }catch (Exception ex1) {
            result = "Exception 错误 ";
        }

        return result;
    }

    public String getFilePath(){
        return this.file_Path;
    }

    public int getFileSize(){
        return this.file_Size;
    }

    public boolean writeFile(byte[] data, String path) {
        File f = null;
        FileOutputStream fos = null;
        try {
            f = new File(path);
            f.createNewFile();
            fos = new FileOutputStream(f);
            fos.write(data, 0, data.length);
        } catch (FileNotFoundException e) {
            return false;
        } catch (IOException e) {
            return false;
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                return false;
            }
        }
        return true;
    }

    public String getFileName(String arg) {
        String path = "";
        if(arg.equals("\"\"")) {
            return null;
        }

        if (arg.indexOf("\"") > -1)
            path = arg.substring(arg.indexOf("\"") + 1, arg.lastIndexOf("\""));
        else
            path = arg;
    //System.out.println("file_path:"+arg);
        path = path.substring(path.lastIndexOf("\\") + 1);
        return path;
    }


    //判断两个byte数组的值是否相等
    private boolean arrayEquals(byte[] src, byte[] value){
        if(src == null || value == null)
            return false;
        if(src.length != value.length)
            return false;

        for(int i=0; i<src.length; i++) {
            if(src[i] != value[i])
                return false;
        }
        return true;
    }


    //找出value数组在src中的位置, 从前往后
    private int arrayIndexOf(byte[] src, byte[] value){
        if(src == null || value == null)
            return -1;
        if(src.length < value.length)
            return -1;

        int postion = -1;

        for(int i=0; i<src.length - value.length; i++) {
            postion = i;
            byte[] tmp = new byte[value.length];
            System.arraycopy(src, i, tmp, 0, tmp.length);
            if(arrayEquals(tmp, value)) {
                tmp = null;
                return postion;
            }else{
                postion = -1;
                tmp = null;
            }
        }

        return postion;
    }


    //找出value数组在src中的位置
    private int arrayLastIndexOf(byte[] src, byte[] value){
        if(src == null || value == null)
            return -1;
        if(src.length < value.length)
            return -1;

        int postion = -1;

        for(int i=src.length - value.length ; i >-1; i--) {
            postion = i;

            byte[] tmp = new byte[value.length];
            System.arraycopy(src, i, tmp, 0, tmp.length);
//System.out.println(i);
//Common.PrintDataHex(tmp, " ");
//Common.PrintDataHex(value, " ");

            if(arrayEquals(tmp, value)) {
                tmp = null;
                return postion;
            }else{
                postion = -1;
                tmp = null;
            }
        }
        //System.out.println("debug");
        return postion;
    }
    

    public HashMap parseAnotherParam(String str){
      HashMap<String, String> hm= new HashMap<String, String>();
      String key="";
      String value="";
      int startindex = 0;
      int endindex = 0;

      startindex = str.indexOf("Content-Disposition: form-data; name=\"")
                 + "Content-Disposition: form-data; name=\"".length();
      endindex = str.indexOf("\"\r\n\r\n");

      while ( startindex >-1 && endindex > -1 ){
        key = str.substring(startindex, endindex);

        if(!str.substring(endindex , endindex + 5).equals("\"\r\n\r\n")  ){//去掉没有value的元素
            str = str.substring(endindex);
            startindex = str.indexOf("Content-Disposition: form-data; name=\"")
                       + "Content-Disposition: form-data; name=\"".length();
            endindex = str.indexOf("\"\r\n\r\n");
            continue;
        }
        if( key.indexOf("\";") > -1){//去掉上传文件的参数以及编码
           str = str.substring(str.indexOf("\";") + 2);
           startindex = str.indexOf("Content-Disposition: form-data; name=\"")
                      + "Content-Disposition: form-data; name=\"".length();
           endindex = str.indexOf("\"\r\n\r\n");

           continue;
        } else
            str = str.substring(endindex + 5);

        value = str.substring(0, str.indexOf("\r\n"));
        str = str.substring(str.indexOf("\r\n") + 2);
        //System.out.println("key:"+key+" value:"+value);
        hm.put(key,value);

        startindex = str.indexOf("Content-Disposition: form-data; name=\"")
                   + "Content-Disposition: form-data; name=\"".length();
        endindex = str.indexOf("\"\r\n\r\n");

      }
      return hm;
    }

    public String getParameter(String param){
        //System.out.println(hm.toString());
      return (String)hm.get(param);
    }




}





调用方式如下:
 
    com.khan.web.uploadFile  upload = new com.khan.web.uploadFile();

//上传文件
    out.print("<p><a>文件上传状态:" + upload.upLoad(request) + "</a></p>");
//取得上传文件的大小
    strs[0][5] = String.valueOf(upload.getFileSize()) ;

//取得跟随文件一起提交的表单中其他参数
    String filepath  = upload.getParameter("filepath");
    String file_type = upload.getParameter("file_type");
    String songstyle = upload.getParameter("songstyle");


2006-8-17 15:38 修正文件上传后会附加一段乱码的bug
计划下一步增加同时上传多个文件的功能

 


posted on 2006-08-11 15:49 Khan 阅读(11752) 评论(7)  编辑 收藏 引用 所属分类: 跨平台开发Java

评论

# re: java 上传文件代码,支持中文文件名和中文文件内容,可以同时提交多个参数  回复  更多评论   

发现处理1m以上的文件上传后不能使用,过段时间再改这个

修正. 不是1m以上的文件上传不正确. 而是二进制文件上传后不能使用, 现已修正此问题...
多文件同时上传仍旧不支持.. 等我有空再说吧...
2006-09-28 10:15 | Khan's Notebook

# re: java 上传文件代码,支持中文文件名和中文文件内容,可以同时提交多个参数  回复  更多评论   

请问一下,是否必须上传文件之后才可以取得表单的其他参数呢?我用jspsamrtupload组件,必须要有文件上传才可以取得表单里的其他参数,但是因为我上传文件是有选择性的,所以不需要每次都上传,因此不能满足需求,不知道你有没有其他的方法可以满足我的要求呢?能不能帮个忙?谢谢了
2006-12-31 15:58 | Noriko

# re: java 上传文件代码,支持中文文件名和中文文件内容,可以同时提交多个参数  回复  更多评论   

如果没有文件上传..就按照普通的方式取得参数, request方式....
这个部分多用嗅探器检测一下http协议的数据包就知道了
2007-01-05 12:38 | Khan's Notebook

# re: java 上传文件代码,支持中文文件名和中文文件内容,可以同时提交多个参数  回复  更多评论   

好是好.就是太长了
2008-06-18 10:04 | 疯子

# re: java 上传文件代码,支持中文文件名和中文文件内容,可以同时提交多个参数  回复  更多评论   

你如果看过jspsamrtupload的代码. 就知道长是什么概念了...
300行代码搞定文件上传. 我自己还是比较满意的
2008-06-18 13:07 | 思春贴调查员

# re: java 上传文件代码,支持中文文件名和中文文件内容,可以同时提交多个参数  回复  更多评论   

太长了 内容太繁琐!
2009-07-29 11:25 | 新手

# re: java 上传文件代码,支持中文文件名和中文文件内容,可以同时提交多个参数  回复  更多评论   

有没有不用组件就可以直接上传的java代码?
2012-05-10 17:40 | 疯言疯语

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理