asp.net

一个简单的asp.net 管理Web站点文件的页面程序

2013-10-30

先看效果

 

WebFileManager

 代码如下
<!--
Author: 张浩华
DateTime: 2012-07-06 03:25
-----------------------------------
管理Web站点下文件的页面程序。
提供上传、重命名、删除、创建文件夹、下载等功能。
-->
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    string Msg = string.Empty;
    static string _CURRENT_PATH = "";
   
    protected void Page_Load(object sender, EventArgs e)
    {
        InitFiles();
        switch (Request["action"])
        {
            case "Root":
                Root();
                break;
            case "Back":
                Back();
                break;
            case "Open":
                Open(Request["FileName"]);
                break;
            case "Delete":
                Delete(Request["FileName"]);
                break;
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (fuFile.HasFile)
        {
            string currentPath = GetCurrentPath();
            string fileName = fuFile.FileName;
            if (rbCover.Checked)
            {
            }
            else if (rbRename.Checked)
            {
                while (System.IO.File.Exists(currentPath + fileName))
                {
                    fileName = "new_" + fileName;
                }
            }
            fuFile.SaveAs(currentPath + fileName);
        }
        InitFiles();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string oleFileName = hfOldName.Value;
        string newFileName = txtNewName.Text;
        if (string.IsNullOrEmpty(newFileName))
        {
            Msg = "The file name can't for empty !";
            return;
        }
       
        string currentPath = GetCurrentPath();
        string oldPath = currentPath + oleFileName;
        string newPath = currentPath + newFileName;
        if (IsFile(oldPath))
        {
            if (System.IO.File.Exists(newPath))
            {
                Msg = "The file name repeated, please reset.";
                return;
            }
            System.IO.File.Move(oldPath, newPath);
        }
        else
        {
            if (string.IsNullOrEmpty(oleFileName))
            {
                System.IO.Directory.CreateDirectory(newPath);
            }
            else
            {
                System.IO.Directory.Move(oldPath, newPath);
            }
        }
        InitFiles();
    }

    private void Back()
    {
        string path = GetCurrentPath();
        string parent = new System.IO.DirectoryInfo(path).Parent.FullName + "\";
        if (parent.IndexOf(Server.MapPath("~/")) >= 0)
        {
            _CURRENT_PATH = parent;
        }
        Response.Redirect(Request.Url.AbsolutePath);       
    }
   
    private void Delete(string filename)
    {
        if (string.IsNullOrEmpty(filename)) return;
        string currentPath = GetCurrentPath();
        string path = currentPath + filename;
        if (IsFile(path))
        {
            System.IO.File.Delete(path);
        }
        else
        {
            try { System.IO.Directory.Delete(path, false); }
            catch { }
        }
        Response.Redirect(Request.Url.AbsolutePath);
    }
   
    protected string GetCreateTime(string name)
    {
        string currentPath = GetCurrentPath();
        string path = currentPath + name;
        return System.IO.File.GetCreationTime(path).ToString("yyyy-MM-dd HH:mm:ss");
    }

    private string GetCurrentPath()
    {
        return string.IsNullOrEmpty(_CURRENT_PATH) ? Server.MapPath("~/") : _CURRENT_PATH;
    }

    protected string GetIcon(string name)
    {
        string currentPath = GetCurrentPath();
        string path = currentPath + name;
        if (IsFile(path))
        {
            int dotPlace = name.LastIndexOf('.');
            if (dotPlace < 0)
            {
                return "";
            }
            else
            {
                return name.Substring(dotPlace + 1);
            }
        }
        else
        {
            return "{DIR}";
        }
    }

    protected string GetSize(string name)
    {
        string currentPath = GetCurrentPath();
        string path = currentPath + name;
        if (IsFile(path))
        {
            long length = new System.IO.FileInfo(path).Length;
            return ((length / 1024) + 1) + " KB (" + length + "B)";
        }
        else
        {
            return "unknow";
        }
    }

    protected string GetUpdateTime(string name)
    {
        string currentPath = GetCurrentPath();
        string path = currentPath + name;
        return System.IO.File.GetLastWriteTime(path).ToString("yyyy-MM-dd HH:mm:ss");
    }
   
    private void InitFiles()
    {
        string currentPath = GetCurrentPath();
        string[] directorys = System.IO.Directory.GetDirectories(currentPath);
        string[] files = System.IO.Directory.GetFiles(currentPath);
        System.Collections.Generic.IList<string> arr = new System.Collections.Generic.List<string>();
        foreach (string s in directorys)
        {
            arr.Add(s.Replace(currentPath, ""));
        }
        foreach (string s in files)
        {
            arr.Add(s.Replace(currentPath, ""));
        }

        rptFile.DataSource = arr;
        rptFile.DataBind();  
    }
   
    private bool IsFile(string path)
    {
        return System.IO.File.Exists(path);
    }

    private void Open(string fileName)
    {
        string currentpath = GetCurrentPath();
        string path = currentpath + fileName;

        if (IsFile(path))
        {
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.WriteFile(fileInfo.FullName);
            Response.Flush();
            Response.End();
           
        }
        else
        {
            _CURRENT_PATH = path + "\";
            Response.Redirect(Request.Url.AbsolutePath);
        }
    }
   
    private void Root()
    {
        _CURRENT_PATH = Server.MapPath("~/");
        Response.Redirect(Request.Url.AbsolutePath);
    }
   
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body{ margin:0; padding:10px; background:#aaf; font-family:Arial 宋体; font-size:14px; }

        #container{ border:1px #ddd solid;}
        #menu{ background-color:#ccc; }
        #menu .line{ border-left:solid 1px #fff; width:0; }
        #menu a{ display:inline-block; margin:0; padding:8px 12px; text-decoration:none;  }
        #menu a:active,#menu a:hover{ background-color:#ddd;  }
       
        #main{ height:450px; }
        #main .file{ float:left; width:100px; height:60px; margin:8px; padding:5px; overflow:hidden; text-align:center; }
        #main .file .icon{ margin:0 5px; font-family:Impact,Arial Black; font-size:30px; width:85px; height:40px; overflow:hidden; }
        #main .file .name{ font-size:12px; }

        #main, #upload_panel, #rename_panel{ background-color:#fff; border:1px #ddd solid; border-left:0; border-right:0; }
        #upload_panel, #rename_panel{ padding:10px; }

        #status_bar{ background-color:#ccc; }
        #status_bar span{ display:inline-block; margin:0; padding:5px 30px 5px 8px; border-left:solid 1px #ddd; }
    </style>
    <script type="text/javascript">
        var Page = { CurrentFile: null };

        /× 页面加载 ×/
        function PageLoad() {
            InitMenu();
            InitFile();
            InitStatusBar();
            InitPanel();
            ShowMessage();
        }

        /× 初始化菜单 ×/
        function InitMenu() {
            /× 页面加载事件,处理初始化页面操作 ×/
            var menuItems = document.getElementById("menu").childNodes;
            for (var menu in menuItems) {
                if (menu >= 0 && (menuItems[menu].tagName + "").toUpperCase() == "A") {
                    var a = menuItems[menu];
                    a.onclick = ClickMenuItem;
                }
            }
        }

        /× 初始化文件列表事件 ×/
        function InitFile() {
            var files = document.getElementById("main").childNodes;
            for (var k in files) {
                if (k >= 0 && (files[k].className + "").toLowerCase().indexOf("file") >= 0) {
                    var file = files[k];
                    file.style.cursor = "pointer";
                    file.onclick = ClickFile;
                }
            }
        }

        /× 初始化“上传文件”和“修改文件名”模块 ×/
        function InitPanel() {
            document.getElementById("upload_panel").style.display = "none";  //隐藏上传文件模块
            document.getElementById("rename_panel").style.display = "none";  //隐藏修改文件名模块
            document.getElementById("fuFile").value = "";  //清空上传文件控件
            document.getElementById("txtNewName").value = "";  //清空名称文本框
            document.getElementById("hfOldName").value = "";  //清空名称文本框
            document.getElementsByName("btnCancel")[0].onclick = InitPanel;  //绑定 Cancel 按钮 Click 事件
            document.getElementsByName("btnCancel")[1].onclick = InitPanel;  //绑定 Cancel 按钮 Click 事件
        }

        /× 初始化状态栏 ×/
        function InitStatusBar() {
            var statusItems = document.getElementById("status_bar").childNodes;
            for (var itemKey in statusItems) {
                if (itemKey >= 0 && (statusItems[itemKey].tagName + "").toUpperCase() == "SPAN") {
                    var span = statusItems[itemKey];
                    var value = Page.CurrentFile == null ? "" : Page.CurrentFile.getAttribute(span.className);
                    if ("filename" == span.className.toLowerCase()) span.innerHTML = "FileName: " + value;
                    if ("type" == span.className.toLowerCase()) span.innerHTML = "Type: " + value;
                    if ("size" == span.className.toLowerCase()) span.innerHTML = "Size: " + value;
                    if ("create_time" == span.className.toLowerCase()) span.innerHTML = "CreateTime: " + value;
                    if ("update_time" == span.className.toLowerCase()) span.innerHTML = "LastUpdateTime: " + value;
                }
            }
        }

        /× 单击菜单项事件 ×/
        function ClickMenuItem() {
            InitPanel();
            var id = this.id;

            switch (id) {
                case "Root":
                    location.search = 'action=Root';
                    break;
                case "Back":
                    location.search = 'action=Back';
                    break;
                case "Open":
                    Open();
                    break;
                case "NewFolder":
                    document.getElementById("rename_panel").style.display = "";
                    break;
                case "Upload":
                    document.getElementById("upload_panel").style.display = "";
                    break;
                case "Rename":
                    Rename();
                    break;
                case "Delete":
                    Delete()
                    break;
            }

            return false;  //不响应超链接跳转操作
        }

        /× 单击文件事件 ×/
        function ClickFile() {
            if (Page.CurrentFile != null) {
                Page.CurrentFile.style.background = "";
            }

            if (Page.CurrentFile == this) {
                Page.CurrentFile.style.background = "";
                Page.CurrentFile = null;
            } else {
                this.style.background = "#ddd";
                Page.CurrentFile = this;
            }
            InitStatusBar();
            InitPanel();
        }

        function Delete() {
            if (Page.CurrentFile != null) {
                location.search = 'action=Delete&FileName=' + Page.CurrentFile.getAttribute("filename");
            }
        }

        function Open() {
            if (Page.CurrentFile != null) {
                location.search = 'action=Open&FileName=' + Page.CurrentFile.getAttribute("filename");
            }
        }

        function Rename() {
            if (Page.CurrentFile != null) {
                document.getElementById("txtNewName").value = Page.CurrentFile.getAttribute("filename");
                document.getElementById("hfOldName").value = Page.CurrentFile.getAttribute("filename");
                document.getElementById("rename_panel").style.display = "";
            }
        }

        function ShowMessage() {
            var msg = "<%=Msg %>";
            if (msg != "") {
                alert(msg);
            }
        }
    </script>
</head>
<body onload="PageLoad()">
    <form id="form1" runat="server">
    <div id="container">
        <div id="menu">
            <a href="#" id="Root">Root</a>
            <a href="#" id="Back">Back</a>
            <a href="#" id="Open">Open(Download)</a>
            <a class="line"></a>
            <a href="#" id="NewFolder">NewFolder</a>
            <a href="#" id="Upload">Upload</a>
            <a href="#" id="Rename">Rename</a>
            <a href="#" id="Delete">Delete</a>
        </div>
        <div id="main">
            <asp:Repeater ID="rptFile" runat="server">
                <ItemTemplate>
            <div class="file"
                filename="<%# Container.DataItem %>"
                size="<%# GetSize(Container.DataItem + "") %>"
                type="<%# GetIcon(Container.DataItem + "") %>"
                create_time="<%# GetCreateTime(Container.DataItem + "") %>"
                update_time="<%# GetCreateTime(Container.DataItem + "") %>">
                <div class="icon"><%# GetIcon(Container.DataItem + "") %></div>
                <div class="name"><%# Container.DataItem %></div>
            </div>
                </ItemTemplate>
            </asp:Repeater>
            <div style="clear:both;"></div>
        </div>
        <div id="upload_panel">
            <asp:FileUpload ID="fuFile" runat="server" />&nbsp;
            <asp:RadioButton ID="rbCover" runat="server" GroupName="FileReapter" Text="Cover" Checked="true" />
            <asp:RadioButton ID="rbRename" runat="server" GroupName="FileReapter" Text="Rename" />&nbsp;
            <asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />&nbsp;
            <input name="btnCancel" type="button" value="Cancel" />
        </div>
        <div id="rename_panel">
            <asp:TextBox ID="txtNewName" runat="server" Text="asdf"></asp:TextBox>&nbsp;
            <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />&nbsp;
            <input name="btnCancel" type="button" value="Cancel" />
            <asp:HiddenField ID="hfOldName" runat="server" />
        </div>
        <div id="status_bar">
            <span class="filename">名称:</span>
            <span class="type">类型:</span>
            <span class="size">大小:</span>
            <span class="create_time">创建时间:</span>
            <span class="update_time">修改时间:</span>
        </div>
    </div>
    </form>
</body>
</html>