<%@ page import="java.util.*,java.net.*,java.text.*,java.util.zip.*,java.io.*"%>
<%@ page contentType="text/html;charset=gb2312"%> 
<%!//编辑器显示列数
private static final int EDITFIELD_COLS =100;
//编辑器显示行数
private static final int EDITFIELD_ROWS = 30;
//-----------------------------------------------------------------------------//改变上传文件是的缓冲目录(一般不需要修改)
private static String tempdir = ".";public class FileInfo{
    public String name            = null,
                   clientFileName  = null,
                   fileContentType = null;
    private byte[] fileContents    = null;
    public File  file              = null;
    public StringBuffer sb = new StringBuffer(100);
    public void setFileContents(byte[] aByteArray){
        fileContents = new byte[aByteArray.length];
        System.arraycopy(aByteArray, 0, fileContents, 0, aByteArray.length);
    }
}public class HttpMultiPartParser{
    private final String lineSeparator = System.getProperty("line.separator", "\n");
    private final int ONE_MB=1024*1024*1;    public Hashtable processData(ServletInputStream is, String boundary, String saveInDir)
                             throws IllegalArgumentException, IOException {
        if (is == null) throw new IllegalArgumentException("InputStream");
        if (boundary == null || boundary.trim().length() < 1)
            throw new IllegalArgumentException("boundary");
        boundary = "--" + boundary;
        StringTokenizer stLine = null, stFields = null;
        FileInfo fileInfo = null;
        Hashtable dataTable = new Hashtable(5);
        String line = null, field = null, paramName = null;
        boolean saveFiles=(saveInDir != null && saveInDir.trim().length() > 0),
                isFile = false;
        if (saveFiles){
            File f = new File(saveInDir);
            f.mkdirs();
        }
        line = getLine(is);
        if (line == null || !line.startsWith(boundary))
            throw new IOException("未发现;"
                                 +" boundary = " + boundary
                                 +", line = "    + line);
        while (line != null){
            if (line == null || !line.startsWith(boundary)) return dataTable;
            line = getLine(is);
            if (line == null) return dataTable;
            stLine = new StringTokenizer(line, ";\r\n");
            if (stLine.countTokens() < 2) throw new IllegalArgumentException("出现错误!");
            line = stLine.nextToken().toLowerCase();
            if (line.indexOf("form-data") < 0) throw new IllegalArgumentException("出现错误!");
            stFields = new StringTokenizer(stLine.nextToken(), "=\"");
            if (stFields.countTokens() < 2) throw new IllegalArgumentException("出现错误!");
            fileInfo = new FileInfo();
            stFields.nextToken();
            paramName = stFields.nextToken();
            isFile = false;
            if (stLine.hasMoreTokens()){
                field    = stLine.nextToken();
                stFields = new StringTokenizer(field, "=\"");
                if (stFields.countTokens() > 1){
                    if (stFields.nextToken().trim().equalsIgnoreCase("filename")){
                        fileInfo.name=paramName;
                        String value = stFields.nextToken();
                        if (value != null && value.trim().length() > 0){
                            fileInfo.clientFileName=value;
                            isFile = true;
                        }
                        else{
                            line = getLine(is); // 去掉"Content-Type:"行
                            line = getLine(is); // 去掉空白行
                            line = getLine(is); // 去掉空白行
                            line = getLine(is); // 定位
                            continue;
                        }
                    }
                }
                else if (field.toLowerCase().indexOf("filename") >= 0){
                            line = getLine(is); // 去掉"Content-Type:"行
                            line = getLine(is); // 去掉空白行
                            line = getLine(is); // 去掉空白行
                            line = getLine(is); // 定位
                    continue;
                }
            }
            boolean skipBlankLine = true;
            if (isFile){
                line = getLine(is);
                if (line == null) return dataTable;
                if (line.trim().length() < 1) skipBlankLine = false;
                else{
                    stLine = new StringTokenizer(line, ": ");
                    if (stLine.countTokens() < 2)
                        throw new IllegalArgumentException("出现错误!");
                    stLine.nextToken(); 
                    fileInfo.fileContentType=stLine.nextToken();
                }
            }
            if (skipBlankLine){
                line = getLine(is);
                if (line == null) return dataTable;
            }
            if (!isFile){
                line = getLine(is);
                if (line == null) return dataTable;
                dataTable.put(paramName, line);
                //判断是否为目录
                if (paramName.equals("dir")){
                  saveInDir = line;
                  //System.out.println(line);
                }
                line = getLine(is);
                continue;
            }
            try{
                OutputStream os = null;
                String path     = null;
                if (saveFiles)
                    os = new FileOutputStream(path = getFileName(saveInDir,
                                               fileInfo.clientFileName));
                else os = new ByteArrayOutputStream(ONE_MB);
                boolean readingContent = true;
                byte previousLine[] = new byte[2 * ONE_MB];
                byte temp[] = null;
                byte currentLine[] = new byte[2 * ONE_MB];
                int read, read3;
                if ((read = is.readLine(previousLine, 0, previousLine.length)) == -1) {
                    line = null;
                    break;
                }
                    while (readingContent){
                        if ((read3 = is.readLine(currentLine, 0, currentLine.length)) == -1) {
                            line = null;
                            break;
                        }
                        if (compareBoundary(boundary, currentLine)){
                            os.write( previousLine, 0, read );
                            os.flush();
                            line = new String( currentLine, 0, read3 );
                            break;
                        }
                        else{
                            os.write( previousLine, 0, read );
                            os.flush();
                            temp = currentLine;
                            currentLine = previousLine;
                            previousLine = temp;
                            read = read3;
                        }
                    }
                os.close();
                temp = null;
                previousLine = null;
                currentLine = null;
                if (!saveFiles){
                  ByteArrayOutputStream baos = (ByteArrayOutputStream)os;
                  fileInfo.setFileContents(baos.toByteArray());
                }
                else{
                  fileInfo.file = new File(path);
                  os = null;
                }
                dataTable.put(paramName, fileInfo);
            }
            catch (IOException e) {
              throw e;
            }
        }
        return dataTable;
    }

解决方案 »

  1.   

    // 比较数据
        private boolean compareBoundary(String boundary, byte ba[]){
            byte b;
            if (boundary == null || ba == null) return false;
            for (int i=0; i < boundary.length(); i++)
               if ((byte)boundary.charAt(i) != ba[i]) return false;
            return true;
        }
    //下载文件
    else if (request.getParameter("downfile")!=null){
      String filePath = request.getParameter("downfile");
      filePath=new String (filePath.getBytes("ISO-8859-1"),"gb2312");
      File f = new File(filePath);
      String filename=f.getName();
    //  filename=new String (filename.getBytes("ISO-8859-1"),"gb2312");
    //  System.out.println(filename);
      if (f.exists()&&f.canRead()) {
    response.setContentType ("application/octet-stream;charset=gb2312");
    response.setHeader ("Content-Disposition", "attachment;filename=\""+filename+"\"");
    FileInputStream file = null;
    BufferedInputStream bis = null;
    ServletOutputStream aaa = null;
    BufferedOutputStream bos = null;
    String DLNAME=filePath;
       file=new FileInputStream(DLNAME);
       bis = new BufferedInputStream(file);
       aaa=response.getOutputStream();
       bos = new BufferedOutputStream (aaa);
       byte[] buff = new byte[2048]; 
       int bytesRead=0;
       while((bytesRead = bis.read(buff, 0, buff.length))!=-1) 
       {
         bos.write(buff, 0, bytesRead); 
       }
       file.close();
       bis.close();
       aaa.close();
       bos.close();
         }
         else {
            out.println("<html><body><h1>文件"+f.getAbsolutePath()+
                        "不存在或者无读权限</h1></body></html>");
         }
    }else{
      if (request.getAttribute("dir")==null){
        request.setAttribute ("dir", application.getRealPath("."));
      }
    %>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=gb2312">
        <style type="text/css">
            .login { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; color: #666666; width:320px; }
            .header { font-family:Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; color: #666666; font-weight: bold; }
            .tableHeader { background-color: #c0c0c0; color: #666666;}
            .tableHeaderLight { background-color: #cccccc; color: #666666;}
            .main { font-family:Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; color: #666666;}
            .copy { font-family:Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; color: #999999;}
            .copy:Hover { color: #666666; text-decoration : underline; }
            .button {background-color: #c0c0c0; color: #666666;
                     border-left: 1px solid #999999; border-right: 1px solid #999999;
                     border-top: 1px solid #999999; border-bottom: 1px solid #999999}
            .button:Hover { color: #444444 }
            td { font-family:Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; color: #666666;}
            A { text-decoration: none; }
            A:Hover { color : Red; text-decoration : underline; }
            BODY { font-family:Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; color: #666666;}
        </style>
    <script type="text/javascript">
    <!--
    var check = false;
    function dis(){
      check = true;
    }
      

  2.   

    var DOM = 0, MS = 0, OP = 0;
    function CheckBrowser() {
     if (window.opera) OP = 1;
    // if(document.getElementById) {
    //   DOM = 1;
    // }
    // if(document.all && !OP) {
    //   MS = 1;
    // }
     MS = 1;
    }function selrow (element, i){
      CheckBrowser();
      var erst;
      if ((OP==1)||(MS == 1)) erst = element.firstChild.firstChild;
      else if (DOM == 1) erst = element.firstChild.nextSibling.firstChild;
      //MouseIn
      if (i == 0)
        if (erst.checked == true) element.style.backgroundColor = '#dddddd';
        else element.style.backgroundColor = '#eeeeee';
      //MouseOut
      else if (i == 1){
        if (erst.checked == true) element.style.backgroundColor = '#dddddd';
        else element.style.backgroundColor = '#ffffff';
      }
      //MouseClick
      else if ((i == 2)&&(!check)){
        if (erst.checked == true) element.style.backgroundColor = '#eeeeee';
        else element.style.backgroundColor = '#dddddd';
        erst.click();
      }
      else check = false;
    }
    //-->
    </script>
    <%
    }
    //上传
    if ((request.getContentType()!=null)&&(request.getContentType().toLowerCase().startsWith("multipart"))){
      response.setContentType("text/html");
      HttpMultiPartParser parser = new HttpMultiPartParser();
      boolean error = false;
      try{
        Hashtable ht = parser.processData(request.getInputStream(), "-", tempdir);
        if (ht.get("myFile")!=null){
          FileInfo fi = (FileInfo)ht.get("myFile");
          File f = fi.file;
          //把文件从缓冲目录里复制出来
          String path = (String)ht.get("dir");
          if (!path.endsWith(File.separator)) path = path+File.separator;
          if (!f.renameTo(new File(path+f.getName()))){
            request.setAttribute("message", "无法上传文件.");
            error = true;
            f.delete();
          }
        }
        else{
          request.setAttribute("message", "请选中上传文件!");
          error = true;
        }
        request.setAttribute("dir", (String)ht.get("dir"));
      }
      catch (Exception e){
        request.setAttribute("message", "发生如下错误:"+e+". 上传失败!");
        error = true;
      }
      if (!error) request.setAttribute("message", "文件上传成功.");
    }
    else if (request.getParameter("editfile")!=null){
    %>
    <title>JSP文件管理器-编辑文件:<%=request.getParameter("editfile")%></title>
    </head>
    <body><%
      String encoding="gb2312"; 
      request.setAttribute("dir", null);
      File ef = new File(request.getParameter("editfile"));
    //  BufferedReader reader = new BufferedReader(new FileReader(ef),encoding);
      String disable = "";
      out.print("<form action=\""+browser_name+"\" method=\"Post\">\n"+
                  "<textarea name=\"text\" wrap=\"off\" cols=\""+
                  EDITFIELD_COLS+"\" rows=\""+EDITFIELD_ROWS+"\""+">"+disable);  String c;%></textarea>
      <input type="hidden" name="nfile" value="<%= request.getParameter("editfile")%>">
      <table><tr>
      <td title="Enter the new filename"><input type="text" name="new_name" value="<%=ef.getName()%>"></td>
      <td><input type="Submit" name="Submit" value="保存"></td>
      <td><input type="Submit" name="Submit" value="取消"></td></tr>
      <tr><td><input type="checkbox" name="Backup" checked>覆写</td></tr>
      </table>
      </form>
      </body>
    </html>
    <%
    }
    //保存文件
    else if (request.getParameter("nfile")!=null){
      File f = new File(request.getParameter("nfile"));
      File new_f = new File(getDir(f.getParent(), request.getParameter("new_name")));
      if (request.getParameter("Submit").equals("Save")){
        if (new_f.exists()&&request.getParameter("Backup")!=null){
          File bak = new File(new_f.getAbsolutePath()+".bak");
          bak.delete();
          new_f.renameTo(bak);
        }
        BufferedWriter outs = new BufferedWriter(new FileWriter(new_f));
        outs.write(request.getParameter("text"));
        outs.flush();
        outs.close();
      }
      request.setAttribute("dir", f.getParent());
    }
    //删除文件
    else if ((request.getParameter("Submit")!=null)&&(request.getParameter("Submit").equals("Delete Files"))){
      Vector v = expandFileList(request.getParameterValues("selfile"), true);
      boolean error = false;
      for (int i=v.size()-1;i>=0;i--){
        File f = (File)v.get(i);
        if (!f.canWrite()||!f.delete()){
          request.setAttribute("message", "无法删除文件"+f.getAbsolutePath()+". 删除失败");
          error = true;
          break;
        }
      }
      if ((!error)&&(v.size()>1)) request.setAttribute("message", "All files deleted");
      else if ((!error)&&(v.size()>0)) request.setAttribute("message", "File deleted");
      else if (!error) request.setAttribute("message", "No files selected");
    }
    //建新目录
    else if ((request.getParameter("Submit")!=null)&&(request.getParameter("Submit").equals("Create Dir"))){
      String dir = ""+request.getAttribute("dir");
      String dir_name = request.getParameter("cr_dir");
      String new_dir = getDir (dir, dir_name);
      if (new File(new_dir).mkdirs()){
        request.setAttribute("message", "目录创建完成");
      }
      else request.setAttribute("message", "创建新目录"+new_dir+"失败");
    }
    //创建文件
    else if ((request.getParameter("Submit")!=null)&&(request.getParameter("Submit").equals("Create File"))){
      String dir = ""+request.getAttribute("dir");
      String file_name = request.getParameter("cr_dir");
      String new_file = getDir (dir, file_name);
      //Test, if file_name is empty
      if ((file_name.trim()!="")&&!file_name.endsWith(File.separator)){
        if (new File(new_file).createNewFile()) request.setAttribute("message", "文件成功创建");
        else request.setAttribute("message", "创建文件"+new_file+"失败");
      }
      else request.setAttribute("message", "错误: "+file_name+"文件不存在");
    }
    //转移文件
    else if ((request.getParameter("Submit")!=null)&&(request.getParameter("Submit").equals("Move Files"))){
      Vector v = expandFileList(request.getParameterValues("selfile"), true);
      String dir = ""+request.getAttribute("dir");
      String dir_name = request.getParameter("cr_dir");
      String new_dir = getDir(dir, dir_name);
      boolean error = false;
      if (!new_dir.endsWith(File.separator)) new_dir+=File.separator;
      for (int i=v.size()-1;i>=0;i--){
        File f = (File)v.get(i);
        if (!f.canWrite()||!f.renameTo(new File(new_dir+f.getAbsolutePath().substring(dir.length())))){
          request.setAttribute("message", "不能转移"+f.getAbsolutePath()+".转移失败");
          error = true;
          break;
        }
      }
      if ((!error)&&(v.size()>1)) request.setAttribute("message", "全部文件转移成功");
      else if ((!error)&&(v.size()>0)) request.setAttribute("message", "文件转移成功");
      else if (!error) request.setAttribute("message", "请选择文件");
    }