现在的位置: 首页 > 综合 > 正文

xml数据岛,xsl,javascript,asp.net 的结合使用 web 程序模仿 windows 资源管理器

2011年09月19日 ⁄ 综合 ⁄ 共 15530字 ⁄ 字号 评论关闭
小弟最近用C#写了一个ASP.NET小应用,使用了一些XML和XSL技术,
本应用主要是用ASP.NET应用来模拟一个Windows资源管理器
一个窗体左边为动态加载的文件夹树状列表,而右边能查看某些类型的文件的内容

本网战使用了一些图片,请在相册中查找


站点主页 index.htm 内容


<html>
 <head>
  <TITLE>基于Web的文件查看器</TITLE>
  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 </head>
 <frameset cols="237,767" rows="*">
  <frame src="treeview.aspx">
  <frame name="frameview" src="说明.txt">
 </frameset>
 <noframes>
  <body bgcolor="#FFFFFF" text="#000000">
  </body>
 </noframes>
</html>

文件 说明.txt 内容


             基于Web 的文件浏览查看器
             
             
  本系统为一个ASP.NET应用程序,使用C#语言开发
  
  本系统在一个浏览器/服务器模式下模仿Windows资源管理器的文件系统树状列表
  
  并提供一定类型的文件的查看功能
  
  本系统不是数据库应用系统,因此不需要配置任何数据库
  
  将所有的文件拷贝到一个Web服务器上的某个虚拟目录即可运行
  
  但服务器必须安装 IIS 及 Microsoft .NET Framwork 1.1简体中文版
  
  本系统默认根目录为 D:\ ,但可以在系统运行时修改根目录,也可进入fileview.aspx.cs
  
  中第19行修改默认根目录然后重新编译即可
  
  本系统主页面为 index.htm
  
  本系统为一个ASP.NET应用,因此该程序运行在 ASPNET 用户帐号下,该帐号权限一般比较低
  
  因此若本系统不能查看某个文件目录,此时需要进入相关的系统管理工具设置ASPNET的权限
  
  客户端建议安装 IE6.0及其以上版本
  
  ************** 版权声明 *****************************************************
  
        你可以任意参考修改和引用所有的代码,可将所有的代码
        
        不受限制的使用于任意性质的系统中.
        
        但在使用时请尊重知识产权,修改的时候望手下留情,
        
        请不要窜改或删除可怜巴巴这么一点的知识产权声明
        
        以尊重漫漫长夜辛苦敲键盘的人们的劳动成果
        
                                                  南京 袁永福  2004-8-8
                                                  
                                                  yyf9989@hotmail.com
  
  *************** 文件列表 ****************************************************
  
  bmp.bmp    gif.bmp        htm.bmp        html.bmp  
  jpeg.bmp    jpg.bmp        txt.bmp        new.bmp
  用于在树状列表中表示文件类型的图标BMP文件,其中文件名就是
  适于该图标的文件的扩展名,默认为 new.bmp
  你可以自己添加相应的文件类型的BMP, 所有的这些BMP大小都是 16*16象素
  
  
  child.gif        close.bmp    collapse.gif    expend.gif
  open.bmp        line.gif    lastchild.gif
  用于在树状列表中表现树状结构的图片
  
  
  index.htm            系统主页面,为一个分为左右两个框架的静态HTML页面
  
  fileview.aspx        用于获得文件列表信息及文件信息和内容的ASP.NET页面
  
  treeview.aspx        用于维护树状列表的ASP.NET页面
  
  htmlcontent.xml    为一个XSLT文档,用于根据文件信息来生成显示该文件内容的HTML代码
  
  

文件 treeview.aspx 内容


<%@ Page language="c#" AutoEventWireup="false" Inherits="fileview.treeview" %>
<!-----------------------------------------------------------------------------
  
                       基于Web的文件查看器之文件树状列表
        
        
        本页面综合使用了 ASP.NET , XML ,XSLT 和 DHTML技术
        
        本页面用于维护一个文件树状列表,该树状列表模仿了Windows资源管理器的文件树状列表
        
        你可以任意参考修改和引用所有的代码,可将所有的代码不受限制的使用于任意性质的系统中.
        
        但在使用时请尊重知识产权,修改的时候望手下留情,
        
        请不要窜改或删除可怜巴巴这么一点的知识产权声明
        
                                                南京 袁永福  2004-8-8
                                                  yyf9989@hotmail.com
        
    
------------------------------------------------------------------------------>
<%
    string strPath = this.Request.Form["baseurl"] ;
    if(strPath == null ||  strPath.Trim().Length == 0 )
        strPath = fileview.FileView.BasePath ; // 显示当前根目录
    strPath = strPath.Trim();
    if(strPath.EndsWith("\\")==false)
        strPath = strPath + "\\"; 
    if(System.IO.Directory.Exists(strPath))
        fileview.FileView.BasePath = strPath ;
%>
<HTML>
    <HEAD>
        <title>动态的XML树状列表</title>
        <style> 
            body{    font-family: "宋体"; font-size: 12px} 
            .TreeNode { FONT-SIZE: 12px; CURSOR: hand } 
            .FocusNode { BORDER-RIGHT: #ff0000 1px solid; 
                        BORDER-TOP: #ff0000 1px solid; FONT-SIZE: 12px; MARGIN-BOTTOM: -2px; 
                        BORDER-LEFT: #ff0000 1px solid; CURSOR: hand; COLOR: #ffffff; 
                        BORDER-BOTTOM: #ff0000 1px solid; BACKGROUND-COLOR: #000099; TEXT-ALIGN: left } 
        </style>
    </HEAD>
    <body leftmargin="1" topmargin="1">
        <form id="Form1" method="post">
            <div>
                <span id="maintree" childlist="fileview.aspx?type=list">根节点
                <input type="text" name="baseurl" style="width:72" value="<%= strPath%>" />
                <input type="submit" value="刷新" /></span>
            </div>
        </form>
        <!--
            XML数据岛,在此定义用于进行匹配的XSLT文档,
            该XSLT文档用于支持动态的生成树状列表
        -->
        <xml id="treexsl">
            <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
                <xsl:output method="xml" />
                <xsl:template match="/*">
                    <xsl:variable name="baseurl">
                        <xsl:value-of select="@baseurl" />
                    </xsl:variable>
                    <table border="0" width="100%" cellspacing="0" cellpadding="0" id="createdtable">
                        <xsl:for-each select="*">
                            <!-- 树状列表是按照节点文本进行排序的 -->
                            <xsl:sort select="concat(@file , @text)" />
                            <!-- 计算当前节点的代号 -->
                            <xsl:variable name="nodeid">
                                <xsl:choose>
                                    <xsl:when test="@id!=''">
                                        <xsl:value-of select="concat('ID' , @id)" />
                                    </xsl:when>
                                    <xsl:when test="boolean('true')">
                                        <xsl:value-of select="translate(name(),'.','_')" />
                                    </xsl:when>
                                </xsl:choose>
                            </xsl:variable>
                            <tr>
                                <td valign="top" align="left" width="16">
                                    <xsl:choose>
                                        <xsl:when test="@childlist != ''">
                                            <xsl:if test="position()!=last()">
                                                <xsl:attribute name="background">line.gif</xsl:attribute>
                                            </xsl:if>
                                            <img src="collapse.gif" expend="0">
                                                <xsl:attribute name="id">
                                                    <xsl:value-of select="concat($nodeid,'expend')" />
                                                </xsl:attribute>
                                                <xsl:attribute name="onclick">ExpendNodeByID('<xsl:value-of select="$nodeid" />');</xsl:attribute>
                                            </img>
                                        </xsl:when>
                                        <xsl:when test="boolean('true')">
                                            <xsl:if test="position()!=last()">
                                                <img src="child.gif" />
                                            </xsl:if>
                                            <xsl:if test="position()=last()">
                                                <img src="lastchild.gif" />
                                            </xsl:if>
                                        </xsl:when>
                                    </xsl:choose>
                                </td>
                                <td valign="top" nowrap="1">
                                    <!--
                                        用于生成树状列表的图标HTML代码
                                    -->
                                    <img align="absmiddle" onclick="ExpendNode(this.nextSibling)" width="16" height="16">
                                        <xsl:attribute name="id">
                                            <xsl:value-of select="concat($nodeid,'icon')" />
                                        </xsl:attribute>
                                        <xsl:attribute name="src">
                                            <xsl:choose>
                                                <xsl:when test="@img!=''">
                                                    <xsl:value-of select="@img" />
                                                </xsl:when>
                                                <xsl:when test="@childlist != ''">close.bmp</xsl:when>
                                                <xsl:when test="boolean('true')">default.bmp</xsl:when>
                                            </xsl:choose>
                                        </xsl:attribute>
                                    </img>
                                    <!--  生成树状列表节点的文本 -->
                                    <a class="TreeNode" valign="top" onclick="ExpendNode(this)" target="frameview">
                                        <xsl:attribute name="id">
                                            <xsl:value-of select="$nodeid" />
                                        </xsl:attribute>
                                        <xsl:if test="@href != ''">
                                            <xsl:attribute name="href">
                                                <xsl:value-of select="concat($baseurl , @href)" />
                                            </xsl:attribute>
                                        </xsl:if>
                                        <xsl:if test="@childlist!=''">
                                            <xsl:attribute name="childlist">
                                                <xsl:value-of select="@childlist" />
                                            </xsl:attribute>
                                            <xsl:attribute name="href">
                                                <xsl:value-of select="concat($baseurl , @childlist)" />
                                            </xsl:attribute>
                                        </xsl:if>
                                        <xsl:value-of select="concat( ' ' ,@text)" />
                                    </a>
                                </td>
                            </tr>
                        </xsl:for-each>
                    </table>
                </xsl:template>
            </xsl:stylesheet>
        </xml>
        <script language="javascript">
            <!--         
            var CurrentTreeNode ;    // 定义树状列表的当前节点对象
            var intIDCount            = 1234;    // 定义一个ID号初始值
            var CurrentLoadingID    = "";
            // 初始化XSLT模板
            var xslDoc                = new ActiveXObject("MSXML.DOMDocument");
            xslDoc.async            = false;
            xslDoc.load                (treexsl.XMLDocument);
            
            var resultDoc            = new ActiveXObject("MSXML.DOMDocument");
            resultDoc.onreadystatechange = XMLStateChange ;
            resultDoc.async            = true;
            function XMLStateChange()
            {
                //window.status = resultDoc.readyState ;
                if(resultDoc.readyState == 4 )
                {
                    var objLabel = document.getElementById("loadflag" + intIDCount) ;
                    if(resultDoc.parseError.errorCode != 0)
                        objLabel.innerText = "加载错误:" + resultDoc.parseError.reason ;
                    else
                    {
                        var myObj    = document.getElementById(CurrentLoadingID + "expend");// 获得节点的展开点图片对象
                        var myIcon  = document.getElementById(CurrentLoadingID + "icon");  // 获得节点的图标图片对象
                        var MainObj = document.getElementById(CurrentLoadingID);           // 获得节点的文本对象
                        var myTable ;
                        var strHTML = resultDoc.transformNode(xslDoc) ;
                        
                        window.status = "加载完毕,正在生成子节点列表..." ;
                        MainObj.insertAdjacentHTML("afterEnd", strHTML );
                        MainObj.removeAttribute("childlist");
                        
                        // 获得刚刚加载的子节点表格对象并进行初始化
                        myTable = document.getElementById("createdtable");
                        objLabel.style.display="none";
                        if(myTable != null)
                        {
                            myTable.style.display = "";
                            myTable.id = CurrentLoadingID + "table";
                        }
                        intIDCount ++ ;
                        //myTable.style.display="none";
                        if(myObj != null)
                        {
                            myTable.style.display="";
                            myObj.expend    = "1";
                            myObj.src        = "expend.gif";
                            myIcon.src        = "open.bmp";
                            myIcon.align    = "absmiddle";
                        }
                        window.status = "";
                    }
                }
            }
            // 展开一个树状列表节点并设置为当前节点
            function ExpendNode(obj)
            {
                if( CurrentTreeNode != obj && CurrentTreeNode != null)
                {
                    CurrentTreeNode.className = "TreeNode";
                }
                CurrentTreeNode = obj;
                CurrentTreeNode.className = "FocusNode";
                window.status = obj.innerText ;
                ExpendNodeByID(obj.id);
            }
            
            // 展开指定编号的树状列表的节点,若该节点的子节点未加载则加载之
            function ExpendNodeByID(strID)
            {
                var myObj    = document.getElementById(strID + "expend"); // 获得节点的展开点图片对象
                var myIcon  = document.getElementById(strID + "icon");     // 获得节点的图标图片对象
                var MainObj = document.getElementById(strID);             // 获得节点的文本对象
                var myTable ;
                
                myTable = document.getElementById(strID + "table");         // 获得子节点表格
                if(MainObj != null && MainObj.childlist != null && myTable == null)
                {
                    // 加载子节点
                    MainObj.insertAdjacentHTML("afterEnd",
                    "<div id='loadflag" + intIDCount + "'>  正在加载子节点...</div>");
                    window.status = "正在加载 " + MainObj.innerText + " 的子节点...";
                    CurrentLoadingID    = strID;
                    resultDoc.load(MainObj.childlist);
                    return ;
                }
                
                // 展开或收缩子节点
                if(MainObj != null && myObj != null && myIcon != null && myTable != null )
                {
                    if(myObj.expend=="1")
                    {
                        myTable.style.display="none";
                        myObj.expend    = "0";
                        myObj.src        = "collapse.gif";
                        myIcon.src        = "close.bmp";
                        myIcon.align    = "absmiddle";
                    }
                    else
                    {
                        myTable.style.display="";
                        myObj.expend    = "1";
                        myObj.src        = "expend.gif";
                        myIcon.src        = "open.bmp";
                        myIcon.align    = "absmiddle";
                    }
                    window.status =  "文件夹:" + MainObj.innerText + " 共有子节点 " + myTable.rows.length + " 个";
                }
            }
            
            // 页面加载的时候加载根节点
            ExpendNodeByID("maintree");
            //document.getElementById("maintree").innerText = "根节点";
            
        -->         
        </script>
    </body>
</HTML>

文件 fileview.aspx 该页面的HTML代码只有 

<%@ Page language="c#" Codebehind="fileview.aspx.cs" AutoEventWireup="false" Inherits="fileview.FileView" %>

它的CS源代码为


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace fileview
{
/// <summary>
/// 返回文件列表,单个文件信息和文件所有内容的页面
///
/// 你可以任意参考修改和引用所有的代码,可将所有的代码不受限制的使用于任意性质的系统中.
///
/// 但在使用时请尊重知识产权,修改的时候望手下留情,
///
/// 请不要窜改或删除可怜巴巴这么一点的知识产权声明
///
/// 南京 袁永福 2004-8-8
/// yyf9989@hotmail.com
/// </summary>
public class FileView : System.Web.UI.Page
{
private static string c_BasePath = "D:\\"; // 初始化文件夹路径
private const string c_List = "list"; // 返回文件列表的参数
private const string c_Get = "get"; // 获得文件信息的参数
private const string c_GetFile = "getfile"; // 获得文件内容的参数
private const string c_PreView = "preview"; // 获得图片的预览结果
private static string strViewType = "list" ;
// 文档内容的类型列表
private static System.Collections.Specialized.NameValueCollection myContentTypeList = null;

// 保存文件和目录的全路径名称的列表
static System.Collections.ArrayList myFileList = new ArrayList();
/// <summary>
/// 设置,返回初始化根目录
/// </summary>
public static string BasePath
{
get{ return c_BasePath;}
set
{
c_BasePath = value;
myFileList.Clear();
}
}
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面

string strPath = null;
string strType = null;

// 初始化文档类型列表
if(myContentTypeList == null)
{
myContentTypeList = new System.Collections.Specialized.NameValueCollection();
myContentTypeList.Add("js" ,"text");
myContentTypeList.Add("jsp" ,"text");
myContentTypeList.Add("asp" ,"text");
myContentTypeList.Add("txt" ,"text");
myContentTypeList.Add("cpp" ,"text");
myContentTypeList.Add("c" ,"text");
myContentTypeList.Add("h" ,"text");
myContentTypeList.Add("frm" ,"text");
myContentTypeList.Add("sql" ,"text");
myContentTypeList.Add("cs" ,"text");
myContentTypeList.Add("vb" ,"text");
myContentTypeList.Add("cls" ,"text");
myContentTypeList.Add("java" ,"text");
myContentTypeList.Add("ini" ,"text");
myContentTypeList.Add("resx" ,"text/xml");
myContentTypeList.Add("xml" ,"text/xml");
myContentTypeList.Add("xsd" ,"text/xml");
myContentTypeList.Add("xsl" ,"text/xml");
myContentTypeList.Add("bmp" ,"image/bmp");
myContentTypeList.Add("jpg" ,"image/jpeg");
myContentTypeList.Add("jpeg" ,"image/jpeg");
myContentTypeList.Add("tiff" ,"image/tiff");
myContentTypeList.Add("png" ,"image/png");
myContentTypeList.Add("gif" ,"image/gif");
myContentTypeList.Add("ico" ,"image/x-icon");
myContentTypeList.Add("doc" ,"application/msword");
myContentTypeList.Add("xls" ,"application/x-msexcel");
myContentTypeList.Add("ppt" ,"application/x-mspowerpoint");
myContentTypeList.Add("zip" ,"application/x-zip-compressed");
}
// 分析参数,获得对象编号和参数类型
if(this.Request["viewtype"]!= null)
{
strViewType = this.Request["viewtype"];
return ;
}
int Index = ToInt32Value(this.Request["id"],-1);
strType = this.Request["type"];

if(c_List == strType )
{
// 获得文件列表
if(Index < 0 || Index > myFileList.Count - 1 )
{
myFileList.Clear();
strPath = c_BasePath ;
}
else
{
strPath = (string)myFileList[Index];
}
// 生成描述文件列表的XML文档
System.Xml.XmlDocument myDoc = new System.Xml.XmlDocument();
myDoc.LoadXml("<filelist />");
myDoc.DocumentElement.SetAttribute("text",System.IO.Path.GetFileName(strPath));
myDoc.DocumentElement.SetAttribute("viewtype",strViewType);

if( (System.IO.File.GetAttributes(strPath) & System.IO.FileAttributes.Directory) != 0 )
{
string [] strFiles = System.IO.Directory.GetFileSystemEntries( strPath , "*.*");

for(int iCount = 0 ; iCount < strFiles.Length ; iCount ++)
{
System.Xml.XmlElement myElement = myDoc.CreateElement("file");
myDoc.DocumentElement.AppendChild(myElement);
try
{
myElement.SetAttribute("text",System.IO.Path.GetFileName(strFiles[iCount]));
myElement.SetAttribute("id", myFileList.Count.ToString() );
if( (System.IO.File.GetAttributes(strFiles[iCount]) & System.IO.FileAttributes.Directory) == 0 )
{
// 本路径为一个文件
string strFileExt = System.IO.Path.GetExtension(strFiles[iCount]);

if(strFileExt != null && strFileExt.Length > 0 )
{
strFileExt = strFileExt.Substring(1);
strFileExt = strFileExt.Trim();
// 设置文件的图标
if(strFileExt == "ico")
myElement.SetAttribute("img", "fileview.aspx?type=getfile&id=" + myFileList.Count.ToString());
else
{
if(System.IO.File.Exists(this.MapPath(".") + "\\" + strFileExt + ".bmp"))
myElement.SetAttribute("img", strFileExt + ".bmp");
}
myElement.SetAttribute("type",strFileExt);
}
// 设置树状列表链接URL
// 若为文本文件和图片则直接显示,否则套用XSL格式
string strContentType = myContentTypeList.Get(strFileExt.ToLower());
if( strContentType != null
&& ( strContentType.StartsWith("image/") || strContentType.StartsWith("text")))
{
myElement.SetAttribute("href","fileview.aspx?type=getfile&id=" + myFileList.Count.ToString());
if(strContentType.StartsWith("image/"))
myElement.SetAttribute("imgfile","1");
}
else
myElement.SetAttribute("href","fileview.aspx?id=" + myFileList.Count.ToString());

myElement.SetAttribute("file","1");

myElement.SetAttribute("size",(new System.IO.FileInfo(strFiles[iCount])).Length.ToString() );

}
else
{
// 本路径为一个目录
myElement.SetAttribute("childlist","fileview.aspx?type=list&id=" + myFileList.Count.ToString());
myElement.SetAttribute("file","0");
}
System.DateTime dtmDate = System.IO.File.GetLastAccessTime(strFiles[iCount]);
myElement.SetAttribute("accesstime",dtmDate.ToString("yyyy-MM-dd HH:mm:ss"));
// 向对象路径列表添加项目
myFileList.Add(strFiles[iCount]);
}
catch(Exception ext)
{
myElement.SetAttribute("text","错误:" + ext.Message);
break;
}
}
}
// 输出文件列表文档
this.Response.ContentEncoding = System.Text.Encoding.GetEncoding(936);
this.Response.Write("<?xml version=\"1.0\" encoding=\"GB2312\" ?><?xml-stylesheet type=\"text/xsl\" href=\"htmlcontent.xml\"?>");
this.Response.Write(myDoc.DocumentElement.OuterXml);
//myDoc.Save( this.Response.Output );
}
else if (c_GetFile == strType)
{ // 返回文件内容
if(Index >= 0 && Index < myFileList.Count)
{
string strFile =(string) myFileList[Index];
if( (System.IO.File.GetAttributes(strFile) & System.IO.FileAttributes.Directory) == 0 )
{
if(System.IO.File.Exists(strFile))
{
string strFileExt = GetFileExtension(strFile);
string strContentType = myContentTypeList.Get(strFileExt);
if(this.Request["preview"] != null)
{
if(strContentType.StartsWith("image/"))
{
using(System.Drawing.Image myImg = System.Drawing.Image.FromFile(strFile))
{
if( myImg.Width < 100 )
this.Response.WriteFile(strFile);
else
{
System.Drawing.Image preImg = myImg.GetThumbnailImage(100,100,null,System.IntPtr.Zero);
preImg.Save(this.Response.OutputStream , System.Drawing.Imaging.ImageFormat.Jpeg );
preImg.Dispose();
}
}
}
return ;
}
else
{
if(strContentType == null || strContentType.Length == 0 )
this.Response.WriteFile(strFile);
else
{
if(strContentType == "text")
{
this.Response.ContentEncoding = System.Text.Encoding.GetEncoding(936);
this.Response.ContentType = "text/html";
this.Response.Write("<pre>");
this.Response.WriteFile(strFile);
this.Response.Write("</pre>");
return ;
}
else
{
this.Response.ContentType = strContentType ;
this.Response.WriteFile(strFile);
}
}
}
}
}
}
}
else if ( c_PreView == strType)
{

}
else
{
// 返回文件信息
if(Index >= 0 && Index < myFileList.Count)
{
System.Xml.XmlDocument myDoc = new System.Xml.XmlDocument();
myDoc.LoadXml("<file />");
myDoc.DocumentElement.SetAttribute("type", GetFileExtension((string)myFileList[Index]));
myDoc.DocumentElement.SetAttribute("url", "fileview.aspx?type=getfile&id=" + Index.ToString());
this.Response.Write("<?xml version=\"1.0\" encoding=\"GB2312\" ?><?xml-stylesheet type=\"text/xsl\" href=\"htmlcontent.xml\"?>");
this.Response.Write(myDoc.DocumentElement.OuterXml);
}
}
}
/// <summary>
/// 根据路径获得文件扩展名
/// </summary>
/// <param name="strFile">文件路径</param>
/// <returns>文件扩展名,若不存在扩展名则返回空白字符串</returns>
private string GetFileExtension(string strFile)
{
try
{
string strFileExt = System.IO.Path.GetExtension(strFile);
strFileExt = strFileExt.Substring(1).Trim().ToLower();
return strFileExt ;
}
catch
{
return "";
}
}
/// <summary>
/// 将字符串转换为整数,若转换失败则返回默认值
/// </summary>
/// <param name="strData">字符串</param>
/// <param name="DefaultValue">默认值</param>
/// <returns>转换结果</returns>
private int ToInt32Value(string strData, int DefaultValue )
{
try
{
if(strData == null)
return DefaultValue ;
e

抱歉!评论已关闭.