<!-- enctype的值很重要,upload.jsp为处理上传的jsp-->
<form method="post" action="upload.jsp"
    enctype="multipart/form-data">
    文件:<input type="file" name="file" /><br />
  名字:<input type="text" name="aa"/><br />
    <input type="submit" value="上传" />
</form>

 

需要将cos.jar导入

<%@page contentType="text/html;charset=GBK"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="java.io.*"%>
<%@page import="java.util.*"%>
<%@page import="java.text.*"%>

<%
String saveDir = "E:/";
int maxPostSize = 2000*1024*1024;//1MB
String encoding = "GBK";


  //存放文件描述   String fileDescription[] = {null,null};
 //上传文件名        String fileName = null;
 //上传文件数        int count = 0;


MultipartRequest multi = null;
try{
    multi = new MultipartRequest(request ,
            saveDir , maxPostSize ,encoding);
}catch(IOException e){
    //上传大小超过maxPostSize就会出现IOException
    out.println(e.getMessage());
    return;
}

 

  //取得文件描述
 if(multi.getParameter("aa")!=null){
        fileDescription[0] = multi.getParameter("aa");
 }else{
        fileDescription[0] = "";
 }

//取得所有上传文件名称
 String ContentType="";
      Enumeration filesname = multi.getFileNames();
      while(filesname.hasMoreElements()){
           String name = (String)filesname.nextElement();
           fileName = multi.getFilesystemName(name);
           File f = multi.getFile(name);
           ContentType = fileName.substring(fileName.lastIndexOf(".")+1);
          
           if(fileName!=null){
             count++;
     %>
      <font color = "red">您上传的第<%=count%>个文件:</font><br>
       文件名:<%=fileName%><br>
       文件类型:<%=ContentType%><br>
       文件描述:<%=fileDescription[count-1]%><br><br>
 
     <%
           }//end if
       }//end while


    File file=new File(saveDir+fileName);//旧文件路径  
       SimpleDateFormat   sdFormat   =   new   SimpleDateFormat( "yyyyMMddhhmmssSSS "); 
       Date   currentTime   =   new   Date(); 
       String   myTime   =     sdFormat.format(currentTime);
    if(file.exists()){
                  file.renameTo(new File(saveDir+myTime+"."+ContentType));
    }else{
             try {
                   file.createNewFile();

             } catch (IOException e) {
                    e.printStackTrace();
             }
    }
    out.println("操作完成!");
 %>