ajax+php文件管理器

发现前两年写的一个文件管理器,感觉挺实用的,分享出来,共两个文件file.html,file.php上传到目录中即可,上传功能请自行下载 uploadify 然后在file.html中配置swf的地址即可

file.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>tongjh原创,交流请发邮件至[email protected]</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://demo.jb51.net/js/2011/artDialog/artDialog.source.js?skin=default"></script>
<script type="text/javascript" src="http://www.uploadify.com/wp-content/themes/uploadify/js/jquery.uploadify.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://www.uploadify.com/wp-content/themes/uploadify/style.css" />
<script Charset="GB2312">
$(function(){
	var mypath=‘‘;//当前所在目录
	//跳转至指定目录
	var goDir = function(path){
			mypath = {path:path};//当前所在目录
			$.ajax({
				type:"GET",
				url:"file.php",
				data:mypath,
				dataType:"json",
				success:function(json){
					if(json.error){//没有文件或目录
						html = json.error;
					}else{
						var files = json.files;//得到文件数组json
						var dirs = json.dirs;//得到目录数组json
						var html=‘‘;//最后组合的html
						if(dirs){//显示目录
							$.each(dirs,function(k,v){
								html += ‘<div class="dir" alt="‘+v.path+‘">‘+v.dir+‘</div>‘;
							});
						}
						if(files){
							$.each(files,function(k,v){
								html += ‘<div class="file" alt="‘+v.path+‘">‘+v.file+‘</div>‘;
							});
						}
					}
					$(".box").html(html);//填充HTML
					//完成面包宵导航
					paths = path.split(‘/‘);
					var p = "当前位置:";var pp = "";
					for(i=0;i<paths.length;i++){
						pp += paths[i]+‘/‘;
						str = pp.slice(0,-1);
						p += ‘<span class="position" alt="‘+str+‘">‘+paths[i]+‘</span> -> ‘;
					}
					p = p.slice(0,-4);
					$(".weizhi").html(p);
				 }
			});
		}
	//打开页面直接给出默认目录root为根目录
	 goDir("./");
	//点击目录进入下一层
	$(".box").delegate(‘.dir‘, ‘click‘, function(e){
		var path =$(this).attr("alt");
		goDir(path);
	});
	//点击位置进入位置
	$(".weizhi").delegate(".position","click",function(){
		 var path = $(this).attr("alt");
		 goDir(path);
	});
	// 捕获在目录上的右击事件
    $(".box").delegate(".dir","contextmenu",function(e){
		var offX = e.pageX;//获得鼠标偏移X值
		var offY = e.pageY;//获得鼠标偏移Y值
		//设置右键菜单的位置
		$(this).append(‘<div class="youjian">‘+$(".youjianCopy").html()+‘</div>‘);
		$(".youjian").css({left:offX-5,top:0});
		//绑定右键菜单的PATH
		var path =$(this).attr("alt");
		$(".youjian").attr("alt",path);
		// 拦截右击事件
        return false;
    });
	// 捕获文件上的右击事件
    $(".box").delegate(".file","contextmenu",function(e){
		var offX = e.pageX;//获得鼠标偏移X值
		var offY = e.pageY;//获得鼠标偏移Y值
		//设置右键菜单的位置
		$(this).append(‘<div class="youjian">‘+$(".fileMenu").html()+‘</div>‘);
		$(".youjian").css({left:offX-5,top:0});
		//绑定右键菜单的PATH
		var path =$(this).attr("alt");
		$(".youjian").attr("alt",path);
		// 拦截右击事件
        return false;
    });
	var myDialog;//artDialog窗口
	//文件及文件右键菜单点击管理目录事件
	$(".box,.weizhi").delegate(".youjian li","click",function(event){
		event.stopPropagation();//阻止事件向上冒泡
		var eName = $(this).attr("alt");//点击事件名称
		var eDir = $(this).parent(".youjian").attr("alt");//执行事件的目录
		//删除目录后刷新父目录
		var path = "";//父路径
		var paths = eDir.split(‘/‘);
		for(i=0;i<paths.length-1;i++){
			path += paths[i]+‘/‘;
		}
		var pp = path.slice(0,-1);//去掉最后/的父路径
		if(eName == ‘deledir‘ || eName == ‘deleFile‘){//ajax执行事件删除目录
			$.ajax({
				type:"GET",
				dataType:"json",
				url:"file.php",
				data:"eName="+eName+"&eDir="+eDir,
				success: function(json){
					if(json.ok){
						alert(json.ok);
						goDir(pp);
					}else{
						alert(json.error);
						goDir(pp);
					}
				}
			});
		}else if(eName == ‘editFile‘){//弹出层,编辑文件
			$.ajax({//ajax获得文件的文本内容
				 type:"GET",
				 url:"file.php",
				 dataType:"json",
				 data:"url="+eDir+"&eName="+eName,
				 success: function(json){
					 if(json.fileType == ‘pic‘){//如果是文件
						 var input = ‘<img src="‘+json.fileStr+‘" />‘;
						 var button = ‘‘;
					 }else if(json.fileType == ‘txt‘){//如果是文本
						 var input = ‘<textarea name="fname" id="fname" cols="45" rows="5" style="width:810px;height:510px;">‘+json.fileStr+‘</textarea>‘;
						 var button = ‘<input type="button" id="fbutton" value="提交" />‘;
					 }else{//是不可编辑的文件
						 var input = ‘文件 [<span style="color:red">‘+eDir+‘</span>] 不可编辑‘;
						 var button = ‘‘;
					 }
					myDialog = art.dialog({//弹出编辑框
						  title:‘文件编辑: ‘+eDir,
						  lock: true,
						  background: ‘#000‘,
						  opacity: 0.87,
						  content:‘<form action="" method="get" id="eaction" onsubmit="return false"><div><input name="eName" type="hidden" id="eName" value="fileSave" /><input name="eDir" type="hidden" id="eDir" value="‘+eDir+‘" />‘+input+‘</div><div align="right">‘+button+‘</div></form>‘
					 });
				 }
			});
		}else{//弹出输入文本框,在增加目录、重命名目录、增加文件时需要一个文本框输入input的name
			myDialog = art.dialog({
				  title:‘输入文件或目录名称‘,
				  lock: true,
				  background: ‘#000‘,
				  opacity: 0.87,
				  content:‘<form action="" method="get" id="eaction" onsubmit="return false"><div><input name="eName" type="hidden" id="eName" value="‘+eName+‘" /><input name="eDir" type="hidden" id="eDir" value="‘+eDir+‘" /><input type="input" name="fname" id="fname" /></div><div align="right"><input name="fname" type="button" id="fbutton" value="提交" /></div></form>‘
			 });
		}
	});
	//右键划过管理菜单换背景
	$(".box,.weizhi").delegate(".youjian li","hover",function(){
		$(this).css({background:"#666",color:"#fff"});
	});
	$(".box,.weizhi").delegate(".youjian li","mouseleave",function(){
		$(this).css({background:"#9cc",color:"#000"});
	});
	//划过.dir or .file背景换色 及 右键离开管理目录事件
	$(".box").delegate(".box>div","hover",function(){
		$(this).css({background:"#9cc"}).siblings().css({background:"#fff"});
	});
	$(".box").delegate(".box>div","mouseleave",function(){
		$("div").remove(".youjian");
	});
	//提交对目录的管理事件
	$("body").delegate("#fbutton","click",function(){
		 var formval = $("#eaction").serialize();
		 myDialog.close();//关闭弹出框
		 //ajax提交对目录的管理事件,增加目录、重命名目录、增加文件
		 $.ajax({
			type:"GET",
			dataType:"json",
			url:"file.php",
			data:formval,
			success: function(json){
				if(json.ok){
					alert(json.ok);
					if(json.fname){
						goDir(json.fname);//如果是重命名目录,则刷新当前目录
					}
				}else{
					alert(json.error);
				}
			}
		});
	});
	//文件批量上传
	$(‘#file_upload‘).uploadify({
		‘buttonText‘ : ‘上传文件到本目录‘,
		‘buttonClass‘ : ‘upbtn‘,
		‘width‘:120,
		‘height‘:25,
		‘swf‘      : ‘/jqup/uploadify.swf‘,
		‘uploader‘ : ‘file.php‘,
		‘formData‘ : {‘eName‘:‘uploads‘,‘path‘:mypath},
		‘onUploadSuccess‘ : function(file,data,response){
				alert(data);//提示信息
		},
		‘onUploadStart‘ : function(file) {
            $("#file_upload").uploadify("settings","formData" ,{"path":mypath});//改变上传值
        },
		‘onQueueComplete‘ : function(queueData) {
            alert(‘成功上传‘ + queueData.uploadsSuccessful + ‘个文件,上传失败‘+queueData.uploadsErrored+‘个文件‘);
			goDir(mypath);//跳转到上传目录
        }

	});
	//捕获面包屑导航右击事件
	$(".weizhi").delegate(".position","contextmenu",function(e){
		var offX = e.pageX;//获得鼠标偏移X值
		var offY = e.pageY;//获得鼠标偏移Y值
		//设置右键菜单的位置
		$(".weizhi").append(‘<div class="youjian">‘+$(".youjianCopy").html()+‘</div>‘);
		$(".youjian").css({left:offX-5,top:0});
		//绑定右键菜单的PATH
		var path =$(this).attr("alt");
		$(".youjian").attr("alt",path);
		// 拦截右击事件
        return false;
	});
});
</script>
<style>
.file{color:#00f;cursor:pointer;position:relative;}
.dir{color:#f00;cursor:pointer;position:relative;}
.position{cursor:pointer;}
.youjian{cursor:pointer;width:100px;background:#9cc;position:absolute;z-index:999;overflow:hidden;}
.youjian li{list-style:none;line-height:25px;padding-left:10px;color:#000;}
.upbtn{background:#666666;color:#fff;font-size:14px;text-align:center;}
.weizhi{position:relative;}
 </style>
</head>

<body>
<div class="weizhi">当前位置:</div>
<hr /><input type="file" name="file_upload" id="file_upload" />
<div class="box"></div>
<div class="youjianCopy" style="display:none">
    <li alt="addDir">增加目录</li>
    <li alt="addFile">增加文件</li>
    <li alt="rename">重命名目录</li>
    <li alt="deledir">删除目录</li>
</div>
<div class="fileMenu" style="display:none">
    <li alt="editFile">编辑文件</li>
    <li alt="renameFile">重命名文件</li>
    <li alt="deleFile">删除文件</li>
</div>
</body>
</html>

file.php

<?php
/**
 *  文件操作部分
 *  tongjh原创,交流请发邮件至[email protected]
*/

//文件上传
if($_POST["eName"] == ‘uploads‘){
	$path = ‘/‘.$_POST[‘path‘].‘/‘;//上传路径
	$verifyToken = md5(‘unique_salt‘ . $_POST[‘timestamp‘]);//安全性检测,目录已关闭
	if (!empty($_FILES)) {
		$tempFile = $_FILES[‘Filedata‘][‘tmp_name‘];//上传的文件名称
		$targetPath = $_SERVER[‘DOCUMENT_ROOT‘] . $path;//上传文件的路径
		$targetFile = rtrim($targetPath,‘/‘) . ‘/‘ . $_FILES[‘Filedata‘][‘name‘];//上传的文件位置

		$fileTypes = array(‘jpg‘,‘jpeg‘,‘gif‘,‘png‘); // 允许的上传文件类型
		$fileParts = pathinfo($_FILES[‘Filedata‘][‘name‘]);//上传文件类型

		if (in_array($fileParts[‘extension‘],$fileTypes)) {
			move_uploaded_file($tempFile,$targetFile);
			echo ‘上传文件‘.$targetFile.‘成功‘;
		} else {
			echo ‘上传的文件类型不是允许的‘;
		}
	}
}

//增加目录
if($_GET["eName"] == ‘addDir‘){
	if(file_exists($_GET[‘eDir‘].‘/‘.$_GET[‘fname‘])){
		$msg = array(‘error‘=>‘目录已经存在‘);
	}else{
		if(@mkdir($_GET[‘eDir‘].‘/‘.$_GET[‘fname‘])){
			$msg = array(‘ok‘=>‘成功建立目录‘.$_GET[‘fname‘],‘fname‘=>$_GET[‘eDir‘].‘/‘.$_GET[‘fname‘]);
		}else{
			$msg = array(‘error‘=>‘无法建立目录‘);
		}
	}
	echo json_encode($msg);
}

//重命名目录
if($_GET["eName"] == ‘rename‘){
	$rename = explode(‘/‘,$_GET[‘eDir‘]);
	for($i=0;$i<count($rename)-1;$i++){
		$str .= $rename[$i].‘/‘;
	}
	$rename = $str.$_GET[‘fname‘];
	if(@rename($_GET[‘eDir‘],$rename)){
		$msg = array(‘ok‘=>‘成功重命名目录‘.$rename,‘fname‘=>$rename);
	}else{
		$msg = array(‘error‘=>‘无法重命名目录‘);
	}
	echo json_encode($msg);
}

//删除目录
if($_GET["eName"] == ‘deledir‘){
	if(@rmdir($_GET[‘eDir‘])){
		$msg = array(‘ok‘=>‘成功删除目录 ‘.$_GET[‘eDir‘]);
	}else{
		$msg = array(‘error‘=>‘无法删除目录,可能不是空目录或没有这个目录 ‘.$_GET[‘eDir‘]);
	}
	echo json_encode($msg);
}

//打开目录
if($_GET[‘path‘]){
	$path = $_GET[‘path‘];
	if($path == ‘root‘){$path = $_SERVER[‘DOCUMENT_ROOT‘];}
	$files = getFiles($path);
	echo json_encode($files);
}

//增加文件
if($_GET["eName"] == ‘addFile‘){
	if(@touch($_GET[‘eDir‘].‘/‘.$_GET[‘fname‘])){
		$msg = array(‘ok‘=>‘成功增加文件‘.$_GET[‘fname‘],‘fname‘=>$_GET[‘eDir‘]);
	}else{
		$msg = array(‘error‘=>‘无法建立文件‘);
	}
	echo json_encode($msg);
}

//重命名文件
if($_GET["eName"] == ‘renameFile‘){
	$rename = explode(‘/‘,$_GET[‘eDir‘]);
	for($i=0;$i<count($rename)-1;$i++){
		$str .= $rename[$i].‘/‘;
	}
	$rename = $str.$_GET[‘fname‘];//新文件名
	if(@rename($_GET[‘eDir‘],$rename)){
		$msg = array(‘ok‘=>‘成功重命名文件‘.$rename,‘fname‘=>substr($str,0,-1));
	}else{
		$msg = array(‘error‘=>‘无法重命名文件‘.$rename);
	}
	echo json_encode($msg);
}

//编辑文件
if($_GET["eName"] == ‘editFile‘){
	/*判断文件类型*/
	$finfo = pathinfo($_GET[‘url‘]);
	$filetype = $finfo["extension"];
	$picArray = array(‘jpg‘,‘jpeg‘,‘gif‘,‘png‘,‘ico‘);
	$txtArray = array(‘php‘,‘txt‘,‘inc‘,‘html‘,‘htm‘,‘js‘,‘css‘,‘asp‘);
	if(in_array($filetype,$picArray)){//文件是图片
		$msg["fileStr"] = $_GET[‘url‘];
		$msg["fileType"] = "pic";
	}elseif(in_array($filetype,$txtArray)){//文件是文本类型
		$msg["fileStr"] = gbkToUtf8(@file_get_contents($_GET["url"]));
		$msg["fileType"] = "txt";
	}else{//文件不可编辑
		$msg["fileStr"] = "文件不可编辑";
	}
	echo json_encode($msg);
}

//保存文件
if($_GET["eName"] == ‘fileSave‘){
	if(@file_put_contents($_GET["eDir"],stripslashes($_GET["fname"]))){
		$msg["ok"] = "成功修改文件";
	}else{
		$msg["error"] = "没有找到文件";
	}
	echo json_encode($msg);
}

//删除文件
if($_GET["eName"] == ‘deleFile‘){
	if(@unlink($_GET[‘eDir‘])){
		$msg = array(‘ok‘=>‘成功删除文件 ‘.$_GET[‘eDir‘]);
	}else{
		$msg = array(‘error‘=>‘无法删除文件,请检查是否拥有删除权限 ‘.$_GET[‘eDir‘]);
	}
	echo json_encode($msg);
}

/**
 *  得到一个目录下的所有目录与文件
 * @access    public
 * @param     string  $path  给定的目录
 * @return    array(三维数组) 如果成功返回一个目录下的所有目录和文件,失败返回一个失败提示数组
 */
function getFiles($path){
	if($fh = @opendir($path)){
		while(false !== ($file = readdir($fh))){
			if($file == ‘.‘ || $file == ‘..‘){
				continue;
			}
			$filetype = filetype($path.‘/‘.$file);
			if($filetype == ‘dir‘){
				$files[‘dirs‘][$file][‘dir‘] = $file;
				$files[‘dirs‘][$file][‘path‘] = $path.‘/‘.$file;
			}
			if($filetype == ‘file‘){
				$files[‘files‘][$file][‘file‘] = $file;
				$files[‘files‘][$file][‘path‘] = $path.‘/‘.$file;
			}
		}
		if(is_array($files)){
			return $files;
		}else{
			return array(‘error‘=>‘没有文件‘);
		}
	}else{
		return array(‘error‘=>‘没有目录‘);
	}
}
/**
 *  字符串编码转换,转换成uft8
 */
function gbkToUtf8 ($value) {
	$code = chkCode($value);
	if($code == "GBK"){
		return iconv("GBK", "UTF-8", $value);
	}
	if($code == "GB2312"){
		return iconv("GB2312", "UTF-8", $value);
	}
	if($code == "GB18030"){
		return iconv("GB18030", "UTF-8", $value);
	}
	return $value;
}

/**
 *  获得字符串的编码
 */
function chkCode($string){
	 $code = array(‘UTF-8‘,‘GBK‘,‘GB18030‘,‘GB2312‘);
	 foreach($code as $c){
		 if( $string === iconv(‘UTF-8‘, $c, iconv($c, ‘UTF-8‘, $string))){
			 return $c;
		 }
	 }
}

?>
时间: 2024-08-29 15:12:45

ajax+php文件管理器的相关文章

PHP服务器文件管理器开发小结(一):功能规划

为了更好的学习PHP.AJAX和LAMP等,为搭建PHP服务器打下基础,作者尝试开发一款基于PHP的服务器文件管理器,并且在管理过程中使用AJAX而不刷新页面. 文件管理器包含以下基本操作 当前文件夹 回到首文件夹 回到上一级文件夹 刷新文件夹视图 上传文件 新建文件 新建子文件夹 文件操作 查看内容 编辑内容 下载 重命名 移动 删除 文件夹操作 重命名 删除 基本上实现了以上功能后,一个比较完善的服务器文件管理器就形成了. 注意,本示例仅考虑Apache可操作的权限,不考虑提权的情况. 管理

PHP服务器文件管理器开发小结(总结):总结、索引和源代码

PHP服务器文件管理器的开发经过前一阶段的介绍基本完成了功能搭建,包括目录的检索.增加.删除.重命名,文件的增加.浏览.修改.重命名.移动,以及文件的上传和下载等功能.本文对前一阶段工作的相关博文进行索引,并提供源代码供有兴趣的同学一同讨论. PHP服务器文件管理器开发小结(一):功能规划 本节讨论了文件管理器的目标功能和运行环境. PHP服务器文件管理器开发小结(二):版面设计和css 本节讨论了页面布局所需的css内容,并介绍了引入jQuery和jQueryUI的方法. PHP服务器文件管理

免费的在线Web文件管理器:Net2FTP,Pydio,eXtplorer,KodExplorer–功能强大

https://www.freehao123.com/web-ftp/ 经常有朋友在使用一些没有带文件管理器的空间时,苦于没有办法来解压上传的文件压缩包,而如果不先上传压缩包,直接上传文件夹的话耗费的时间太多.还有一些朋友希望将空间变成一个文件存储站,这时就需要一个功能足够多也足够强大的在线文件管理器了. 在线的Web文件管理器非常地多,尤其是以PHP在线文件管理器最多,但是真正能够满足我们的文件管理需求同时也容易安装和使用的Web文件管理器不是很多.本篇文章部落就精选四个界面友好.功能丰富和安

介绍分享几款免费的在线Web文件管理器

经常有朋友在使用一些没有带文件管理器的空间时,苦于没有办法来解压上传的文件压缩包,而如果不先上传压缩包,直接上传文件夹的话耗费的时间太多.还有一些朋友希望将空间变成一个文件存储站,这时就需要一个功能足够多也足够强大的在线文件管理器了. 在线的Web文件管理器非常地多,尤其是以PHP在线文件管理器最多,但是真正能够满足我们的文件管理需求同时也容易安装和使用的Web文件管理器不是很多.本篇文章部落就精选四个界面友好.功能丰富和安装方便的Web文件管理器:net2ftp.Pydio.eXtplorer

iOS学习之文件管理器(NSFileManager)和文件对接器(NSFileHandle)

1.文件管理器(NSFileManager) 1> 创建文件夹 创建所需的方法在头文件的声明: /* createDirectoryAtPath:withIntermediateDirectories:attributes:error: creates a directory at the specified path. If you pass 'NO' for createIntermediates, the directory must not exist at the time this

UI14-沙盒机制,文件的读写,文件管理器的增删移动复制,归档和反归档。

1.复杂对象的归档反归档.person类的使用acoder,进行编码.使用decoder进行根据标记,解码. 2.再使用多个person类中,需要转化工具和解转化工具,achiver,unchiever,记得结束要finish. 3.文件管理器 对文件和文件夹的增删改移动. 4.读取沙盒的文件,和三个主要路径 5.简单类的读取写入,string,数组,和字典.

2015 IOS 文件管理器 ——在蓝懿教育 学习笔记

得到文件管理器   蓝懿教育 NSFileManager *fm = [NSFileManager defaultManager]; //    复制 //    [fm copyItemAtPath:@"/Users/ivan/Desktop/a.png" toPath:@"/Users/ivan/Desktop/copy/a.png" error:nil]; //    移动  移动的时候目的地不能有重名的 //    [fm moveItemAtPath:@&

Web 在线文件管理器学习笔记与总结(5)

① 读出要修改的文件的内容 ② 进行修改 ③ 将修改后的内容写进文件 index.php: <?php require 'dir.func.php'; require 'file.func.php'; require 'common.func.php'; $path = 'file'; $info = readDirectory($path); $act = @$_REQUEST['act']; $filename = @$_REQUEST['filename']; //跳转变量 $redire

Web 在线文件管理器学习笔记与总结(2)显示文件列表(名称,类型,大小,可读,可写,可执行,创建时间,修改时间,访问时间)

主要函数: filetype() 判断文件类型 filesize() 得到文件大小(字节) is_readable() 判断文件是否可读 is_writeable() 判断文件是否可写 is_executable() 判断文件是否可执行 filectime() 文件创建时间 filemtime() 文件修改时间 fileatime() 文件访问时间 file.func.php 封装文件操作的文件: <?php /* 转换字节大小 */ function transByte($size){ $ar