一个用ajax 实现 加载所有文件 形成树

来源:互联网 发布:轻电科技淘宝店 编辑:程序博客网 时间:2024/04/27 22:32

用ajax 加载所有的盘符 、文件、文件夹

//JSP页面

<%@page contentType="text/html; charset=GBK"%>

<html>
<head>
<title>index</title>

<link rel="stylesheet" href="css/tree.css" type="text/css"/>
</head>
<body bgcolor="#ffffff">
<form method="post" action="index.jsp">
<div id="Tree"></div>
<!--显示提示-->
<div id="div1"  onmouseleave="clearTbody();" onmousemove="this.style.cursor='hand';" style="display:none; position:absolute ; ">
  <table bgcolor="#f7fff7" style="border:1px solid #666666; ;filter:alpha(opacity=70)" border="0" cellpadding="0" cellspacing="0">
    <tbody id="tbody">    </tbody>
  </table>
</div>
<div id="a"></div>
<!--显示内容-->
<div id="content" style="display:none;"></div>
</form>
<script type="text/javascript" language="javascript">
    var xmlHttp;
    var Tree;
    var flg=false;
    var add;//加载状态
    var div1;//显示提示
    var tbody;
   var content;//显示内容
    function createXMLHttpRequest()
    {
      if(window.ActiveXObject)
      {
         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      else if(window.XMLHttpRequest)
      {
        xmlHttp=new XMLHttpRequest();
      }
    }
    function init()
    {
      Tree=document.getElementById('Tree');
      div1=document.getElementById('div1');
      tbody=document.getElementById('tbody');
      content=document.getElementById('content');
    }
    var path;//得到路径
    function getValue(x)
    {
      path=x;
      init();
      createXMLHttpRequest();
      var url='tree?path='+x+'&d='+new Date().getTime();
      xmlHttp.open('post',url,true);
      xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      xmlHttp.onreadystatechange=call;
      xmlHttp.send(null);
    }
    //当前节点的对象
    var isSe;
     function getValues(se,x)
    {
      content.style.display='none';
      se.src='images/loading.gif';
      isSe=se;
      path=x;
      init();
      createXMLHttpRequest();
      var url='tree?path='+x+'&d='+new Date().getTime();
      xmlHttp.open('post',url,true);
      xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      xmlHttp.onreadystatechange=call;
      xmlHttp.send(null);

    }
    //执行
    var b;
     function execute(se,pa,start)
    {

      se.src='images/loading.gif';
      b=se;
      init();
      createXMLHttpRequest();
      var url='tree?path='+pa+'&start='+start+'&d='+new Date().getTime();
      xmlHttp.open('post',url,true);
      xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      xmlHttp.onreadystatechange=s;
      xmlHttp.send(null);

    }
    //execute
    function s()
    {
     if(xmlHttp.readyState==4)
      {
        if(xmlHttp.status==200)
        {
          if(b !=null)
           b.src='images/sheet.gif';
         // result(xmlHttp.responseXML);

        }
      }
    }
    //得到结果
    function result(xml)
    {
      if(xml==null)
      return;
      var root=xml.getElementsByTagName('root');
      if(root==null)
      return;
      content.innerText=root[0].firstChild.nodeValue;
      content.style.display='block';
    }
    function call()
    {
      if(xmlHttp.readyState==4)
      {
        if(xmlHttp.status==200)
        {
          if(isSe !=null)
          isSe.src=add;
          setTreeView(xmlHttp.responseXML);
        }
      }
    }

    var is=false;
    function setTreeView(xml)
    {
      if(xml == null)
      return;
      var roots=xml.getElementsByTagName('root');
      if(roots.length<=0 || roots == null)
        return;
      var ul=document.createElement('ul');
      for(var i=0;i<roots.length;i++)
      {
        //是否有子节点
        if(roots[i].childNodes[0].nodeValue == 'no')
        {
          //没有
          flg=true;
        }

        if(path == 'root')
        {

          ul.appendChild(createNode(roots[i].childNodes[0].nodeValue,roots[i].childNodes[0].nodeValue,1));
          Tree.appendChild(ul);
        }
        else
        {

          ul.appendChild(createNode(roots[i].childNodes[0].firstChild.nodeValue,roots[i].childNodes[1].firstChild.nodeValue,roots[i].childNodes[2].firstChild.nodeValue,roots[i].childNodes[3].firstChild.nodeValue,roots[i].childNodes[4].firstChild.nodeValue,roots[i].childNodes[5].firstChild.nodeValue,roots[i].childNodes[6].firstChild.nodeValue,roots[i].childNodes[7].firstChild.nodeValue));
          isSe.parentNode.appendChild(ul);
        }
      }
    }

    function createNode(value,p,type,canred,canwriter,hide,modified,length)
    {
      var li =document.createElement('li');
      var image=document.createElement('img');

      var gif; //+-
      var folder;//文件夹图标
      if(!flg && type==1)
      {
        if(isSe == null || isSe== '')
        {
          gif='images/plus.gif';
        }
        else
        {
          var src=isSe.src;
          if(src.indexOf('images/plus.gif')==-1)
          {

            gif='images/plus.gif';
          }
          else
          {
            gif='images/plus.gif';
          }
        }
        folder='images/folder.gif';
      }
      else
      {
        gif='images/blank.gif';
        if(type==2)
        {

          folder='';
        }
        else
        {
          folder='images/sheet.gif';
        }
      }
       image.setAttribute('src',gif);
        image.style.cursor='hand';
      image.onclick=function()
      {
        if(this.src.indexOf('images/plus.gif')!=-1)
        {
          add='images/minus.gif';
           this.src='images/minus.gif';
           is=false;
        }
        else
        {
          is=true;
          this.src='images/plus.gif';
          add='images/plus.gif';
          clearNode(this.nextSibling.nextSibling.nextSibling.nextSibling);
        }
        if(!is)
        {

          getValues(this,this.nextSibling.nextSibling.nextSibling.innerText);
        }
      }
      //文件件夹图标
      var image1=document.createElement('img');
      image1.setAttribute('src',folder);
      if(type==0)
      {
        image1.style.cursor='hand';
        image1.onmouseover=function ()
        {
          var tr1 =document.createElement('tr');
         var tr2 =document.createElement('tr');
          var tr3 =document.createElement('tr');
           var tr4 =document.createElement('tr');
           var tr5 =document.createElement('tr');
          var tr6 =document.createElement('tr');
          var tr7 =document.createElement('tr');
          var tr8 =document.createElement('tr');

          var td1=document.createElement('td');
          var td2=document.createElement('td');
          var td3=document.createElement('td');
          var td4=document.createElement('td');
          var td5=document.createElement('td');
          var td6=document.createElement('td');
          var td7=document.createElement('td');
          var td8=document.createElement('td');
          td1.appendChild(document.createTextNode('说明:'+value));
          td2.appendChild(document.createTextNode('位置:'+p));
          td3.appendChild(document.createTextNode('类型:文件'));
          td4.appendChild(document.createTextNode('可读:'+canred));
          td5.appendChild(document.createTextNode('可写:'+canwriter));
          td6.appendChild(document.createTextNode('是否隐藏:'+hide));
          td7.appendChild(document.createTextNode('最后修改时间:'+modified));
          td8.appendChild(document.createTextNode('大小:'+length));
          tr1.appendChild(td1);
          tr1.onmouseover=function (){suggestOver(this)};
          tr1.onmouseout==function (){suggestOut(this)};
          tr2.appendChild(td2);
           tr2.onmouseover=function(){suggestOver(this)};
          tr2.onmouseout=function(){suggestOut(this)};
          tr3.appendChild(td3);
           tr3.onmouseover=function(){suggestOver(this)};
          tr3.onmouseout=function(){suggestOut(this)};
          tr4.appendChild(td4);
           tr4.onmouseover=function(){suggestOver(this)};
          tr4.onmouseout=function(){suggestOut(this)};
          tr5.appendChild(td5);
           tr5.onmouseover=function(){suggestOver(this)};
          tr5.onmouseout=function(){suggestOut(this)};
          tr6.appendChild(td6);
           tr6.onmouseover=function(){suggestOver(this)};
          tr6.onmouseout=function(){suggestOut(this)};
          tr7.appendChild(td7);
           tr7.onmouseover=function(){suggestOver(this)};
          tr7.onmouseout=function(){suggestOut(this)};
          tr8.appendChild(td8);
           tr8.onmouseover=function(){suggestOver(this)};
          tr8.onmouseout=function(){suggestOut(this)};

          tbody.appendChild(tr1);
          tbody.appendChild(tr2);
          tbody.appendChild(tr3);
          tbody.appendChild(tr4);
          tbody.appendChild(tr5);
          tbody.appendChild(tr6);
          tbody.appendChild(tr7);
          tbody.appendChild(tr8);

          div1.style.display='block';
          div1.style.pixelLeft=this.offsetLeft+this.offsetWidth;
          div1.style.pixelTop=this.offsetTop+this.offsetHeight;

        }
         image1.onmouseout=function ()
         {

           var x=event.x;
           var y=event.y;
           if(x<div1.style.pixelLef || y<div1.style.pixelTop || x>div1.style.pixelLeft+div1.style.offsetWidth || y>div1.style.prixelTop+div1.style.offsetTop)
           clearTbody();
         }
         image1.onclick=function()
         {
           execute(this,p,1);
         }
      }
      //名称
      var text=document.createTextNode(value);
      //一个层
      var div=document.createElement('div');
      div.style.display='none';
      //实际的路径
      var t=document.createTextNode(p);
      div.appendChild(t);
      //+-
      li.appendChild(image);
      //文件夹
      li.appendChild(image1);
      //名称
      li.appendChild(text);
      //路径
      li.appendChild(div);
      return li;
    }
    //清除节点
    function clearNode(node)
    {
      if(node == null)
      return;
      node.parentNode.removeChild(node);
      node.style.display='none';
    }
    //显示信息
    function clearTbody()
    {
      for(var i=tbody.childNodes.length-1;i>=0;i--)
      {
       tbody.removeChild(tbody.childNodes[i]);
       }
       div1.style.display='none';
    }
   function suggestOver(div_value)
  {
    div_value.className='suggest_link_over';
  }
  function suggestOut(div_value)
  {
    div_value.className='suggest_link';
  }

    getValue('root');
</script></body>
</html>
//CSS

 .suggest_link
  {
  background-color:#FFFFFF;
  padding:2px 6px 2px 6px;
  width=180
  }
  .suggest_link_over
  {
  background-color:#E8F2FE;
  padding:2px 6px 2px  6px;
  width=180
  }
 p{
  font-family:arial;
  
 }
 a{
  color:#000;
  font-family:arial;
  font-size:0.8em;
 }
 
 .tree{
  margin:0px;
  padding:0px;
 }
ul{ /*子结点*/
  margin-left:20px; /* Left spacing */
  padding-left:0px;
 }
li{ /* 结点 */
  list-style-type:none;
  vertical-align:middle;
  font-family:arial;
  font-size:1.0em;
  color:red;
 }
li a{ /* 结点连接 */
  color:#000;
  text-decoration:none;
  font-family:arial;
  font-size:0.8em;
  padding-left:2px;
 }

//后台处理类

//实体类

package file;

public class FileBean {
    private String path;
    private String name;
    private String textname;
    private String canwriter;
    private String canred;
    private String hide;
    private String lastmodified;
    private String length;
    public FileBean() {
    }

    public void setPath(String path) {
        this.path = path;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setTextname(String textname) {
        this.textname = textname;
    }

    public void setCanwriter(String canwriter) {
        this.canwriter = canwriter;
    }

    public void setCanred(String canred) {
        this.canred = canred;
    }

    public void setHide(String hide) {
        this.hide = hide;
    }

    public void setLastmodified(String lastmodified) {
        this.lastmodified = lastmodified;
    }

    public void setLength(String length) {
        this.length = length;
    }

    public String getPath() {
        return path;
    }

    public String getName() {
        return name;
    }

    public String getTextname() {
        return textname;
    }

    public String getCanwriter() {
        return canwriter;
    }

    public String getCanred() {
        return canred;
    }

    public String getHide() {
        return hide;
    }

    public String getLastmodified() {
        return lastmodified;
    }

    public String getLength() {
        return length;
    }
}

//读取文件的类

package file;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.jsp.jstl.sql.ResultSupport;

public class getFile {
    public getFile() {
    }

    /**
     *
     * @return File[]
     */
    public static File[] getListRoot() {
        return File.listRoots();
    }

    /**
     *
     * @param url String
     * @return File[]
     */
    public static ArrayList getListFiles(String url) {
        if (url == null || url.equals("")) {
            return null;
        }
        ArrayList ary = new ArrayList();
        File file = new File(url);
        if (file == null) {
            return null;
        }
        File[] files = file.listFiles();

        if (files == null) {
            return null;
        }
        if (files.length > 0 || files != null) {
            for (int i = 0; i < files.length; i++) {
                FileBean f = new FileBean();
                if (files[i].isDirectory()) {
                    f.setName(files[i].getName());
                    f.setPath(files[i].toString());

                }
                else
                {
                    f.setName(files[i].getName());
                    f.setPath(files[i].toString());
                    f.setTextname(files[i].isFile()?"文件":"文件夹");
                    f.setCanred(files[i].canRead()?"可读":"不可读");
                    f.setCanwriter(files[i].canWrite()?"可写":"不可写");
                    f.setHide(files[i].isHidden()?"隐藏":"显示");
                    f.setLastmodified(new Date(files[i].lastModified()).toLocaleString());
                    f.setLength(files[i].length()+"B");
                }
                ary.add(f);
            }
        }
        return ary;
    }
    //用DOS命令打开文件夹
    public static boolean startRunTime(String path)
    {
        if(path == null || path.equals(""))
            return false;
        try {
            Runtime.getRuntime().exec("cmd /c " + path);
            return true;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return false;

    }
    /**
     * 读文件
     * @param pathName String
     * @return String
     */
    public static String randFile(String pathName)
    {
        String content=null;
        if(pathName == null || pathName.equals(""))
            return null;
        try {
            BufferedReader reader = new BufferedReader(new FileReader(pathName));
            String file = reader.readLine();
            while (file != null) {
                content += file;
                file = reader.readLine();
                return content;
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;

    }
}
 //SERVLEt

package file;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class Tree extends HttpServlet {
    private static final String CONTENT_TYPE = "text/xml; charset=gb2312";

    //Initialize global variables
    public void init() throws ServletException {
    }

    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        String pathName = request.getParameter("path");
        String start=request.getParameter("start");
        if (pathName == null || pathName.equals("")) {
            return;
        }
        pathName = new String(pathName.getBytes("ISO8859-1"), "GBK");
        String content=null;
        if(start!=null)
        {

            getFile.startRunTime(pathName);
            out.close();
            return;
        }
        StringBuffer buf = new StringBuffer(
                "<?xml version=/"1.0/" encoding=/"gb2312/"?>");
        buf.append("<roots>");
       
        if (pathName.equals("root")) {
            //得到盘符
            File[] files = getFile.getListRoot();
            for (int i = 0; i < files.length; i++) {
                buf.append("<root>");
                buf.append(files[i].toString());
                buf.append("</root>");
            }
        } else {
            ArrayList ary = getFile.getListFiles(pathName);
            if (ary != null) {
                for (int i = 0; i < ary.size(); i++) {
                    FileBean bean = (FileBean) ary.get(i);
                    buf.append("<root>");
                    buf.append("<name>");
                    buf.append(bean.getName());
                    buf.append("</name>");
                    buf.append("<path>");
                    buf.append(bean.getPath());
                    buf.append("</path>");

                    if (bean.getTextname() == null ||
                        bean.getTextname().equals("")) {

                        buf.append("<type>");
                        buf.append("1");
                        buf.append("</type>");
                        buf.append("<canred>");
                        buf.append("1");
                        buf.append("</canred>");
                        buf.append("<canwriter>");
                        buf.append("2");
                        buf.append("</canwriter>");
                        buf.append("<hide>");
                        buf.append("3");
                        buf.append("</hide>");
                        buf.append("<modified>");
                        buf.append("4");
                        buf.append("</modified>");
                        buf.append("<length>");
                        buf.append("5");
                        buf.append("</length>");

                    } else {
                        buf.append("<type>");
                        buf.append("0");
                        buf.append("</type>");
                        buf.append("<canred>");
                        buf.append(bean.getCanred());
                        buf.append("</canred>");
                        buf.append("<canwriter>");
                        buf.append(bean.getCanwriter());
                        buf.append("</canwriter>");
                        buf.append("<hide>");
                        buf.append(bean.getHide());
                        buf.append("</hide>");
                        buf.append("<modified>");
                        buf.append(bean.getLastmodified());
                        buf.append("</modified>");
                        buf.append("<length>");
                        buf.append(bean.getLength());
                        buf.append("</length>");
                    }
                    buf.append("</root>");

                }
            } else {
                buf.append("<root>");
                buf.append("<name>");
                buf.append("no");
                buf.append("<name>");
                buf.append("<path>");
                buf.append("aa");
                buf.append("</path>");
                buf.append("<type>");
                buf.append("2");
                buf.append("</type>");
                buf.append("<canred>");
                buf.append("1");
                buf.append("</canred>");
                buf.append("<canwriter>");
                buf.append("2");
                buf.append("</canwriter>");
                buf.append("<hide>");
                buf.append("3");
                buf.append("</hide>");
                buf.append("<modified>");
                buf.append("4");
                buf.append("</modified>");
                buf.append("<length>");
                buf.append("5");
                buf.append("</length>");

                buf.append("</root>");
            }
        }
        buf.append("</roots>");
        out.println(buf.toString());
        out.close();
    }

    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }

    //Clean up resources
    public void destroy() {
    }
}

原创粉丝点击