php 简单文件图片上传类

 更新时间:2016年11月25日 16:30  点击:1379
php 简单文件图片上传类

这个文件上传类可以上传gif",".jpg",".jar",".jad",".mid",".mp3",".mid",".bmp",".wav",".rm",".wmv文件格式哦,如果你还想支持其它的话可以设计$this->file_type();就OK了,。

<?php
class upload{

var $file_type;
var $file_size;
var $file_name;
var $exname;
var $datetime;


function up($post_name,$path){
 $this->file_name=$_FILES[$post_name]["name"];
 $this->exname=strtolower(substr($this->file_name,strrpos($this->file_name,".")));
 $this->file_size=$_FILES[$post_name]["size"];
 $this->file_type=array(".gif",".jpg",".jar",".jad",".mid",".mp3",".mid",".bmp",".wav",".rm",".wmv");
 $this->datetime=date("YmdHis");
 if(!in_array($this->exname,$this->file_type)){
  print("<script language='javascript'>");
  print("alert('格式不支持!');");
  print("history.back();");
  print("</script>");
  break;
 }elseif($this->file_size>"50000"){
  print("<script language='javascript'>");
  print("alert('图片大小不能超过50KB!');");
  print("history.back();");
  print("</script>");
  break;
 }else{
  move_uploaded_file($_FILES[$post_name]["tmp_name"],$path.$this->datetime.$this->exname);
  }
}

function fileName(){
   $pic=$this->datetime.$this->exname;
   return $pic;
}

}
?>
 

php 通用的树型类 可以生成任何树型结构


class tree
{
 /**
 * 生成树型结构所需要的2维数组
 * @var array
 */
 var $arr = array();

 /**
 * 生成树型结构所需修饰符号,可以换成图片
 * @var array
 */
 var $icon = array('│','├','└');

 /**
 * @access private
 */
 var $ret = '';

 /**
 * 构造函数,初始化类
 * @param array 2维数组,例如:
 * array(
 *      1 => array('id'=>'1','parentid'=>0,'name'=>'一级栏目一'),
 *      2 => array('id'=>'2','parentid'=>0,'name'=>'一级栏目二'),
 *      3 => array('id'=>'3','parentid'=>1,'name'=>'二级栏目一'),
 *      4 => array('id'=>'4','parentid'=>1,'name'=>'二级栏目二'),
 *      5 => array('id'=>'5','parentid'=>2,'name'=>'二级栏目三'),
 *      6 => array('id'=>'6','parentid'=>3,'name'=>'三级栏目一'),
 *      7 => array('id'=>'7','parentid'=>3,'name'=>'三级栏目二')
 *      )
 */
 function tree($arr=array())
 {
       $this->arr = $arr;
    $this->ret = '';
    return is_array($arr);
 }

    /**
 * 得到父级数组
 * @param int
 * @return array
 */
 function get_parent($myid)
 {
  $newarr = array();
  if(!isset($this->arr[$myid])) return false;
  $pid = $this->arr[$myid]['parentid'];
  $pid = $this->arr[$pid]['parentid'];
  if(is_array($this->arr))
  {
   foreach($this->arr as $id => $a)
   {
    if($a['parentid'] == $pid) $newarr[$id] = $a;
   }
  }
  return $newarr;
 }

    /**
 * 得到子级数组
 * @param int
 * @return array
 */
 function get_child($myid)
 {
  $a = $newarr = array();
  if(is_array($this->arr))
  {
   foreach($this->arr as $id => $a)
   {
    if($a['parentid'] == $myid) $newarr[$id] = $a;
   }
  }
  return $newarr ? $newarr : false;
 }

    /**
 * 得到当前位置数组
 * @param int
 * @return array
 */
 function get_pos($myid,&$newarr)
 {
  $a = array();
  if(!isset($this->arr[$myid])) return false;
        $newarr[] = $this->arr[$myid];
  $pid = $this->arr[$myid]['parentid'];
  if(isset($this->arr[$pid]))
  {
      $this->get_pos($pid,$newarr);
  }
  if(is_array($newarr))
  {
   krsort($newarr);
   foreach($newarr as $v)
   {
    $a[$v['id']] = $v;
   }
  }
  return $a;
 }

    /**
 * 得到树型结构
 * @param int ID,表示获得这个ID下的所有子级
 * @param string 生成树型结构的基本代码,例如:"<option value=$id $selected>$spacer$name</option>"
 * @param int 被选中的ID,比如在做树型下拉框的时候需要用到
 * @return string
 */
 function get_tree($myid, $str, $sid = 0, $adds = '', $str_group = '')
 {
  $number=1;
  $child = $this->get_child($myid);
  if(is_array($child))
  {
      $total = count($child);
   foreach($child as $id=>$a)
   {
    $j=$k='';
    if($number==$total)
    {
     $j .= $this->icon[2];
    }
    else
    {
     $j .= $this->icon[1];
     $k = $adds ? $this->icon[0] : '';
    }
    $spacer = $adds ? $adds.$j : '';
    $selected = $id==$sid ? 'selected' : '';
    @extract($a);
    $parentid == 0 && $str_group ? eval("$nstr = "$str_group";") : eval("$nstr = "$str";");
    $this->ret .= $nstr;
    $this->get_tree($id, $str, $sid, $adds.$k.'&nbsp;',$str_group);
    $number++;
   }
  }
  return $this->ret;
 }
    /**
 * 同上一方法类似,但允许多选
 */
 function get_tree_multi($myid, $str, $sid = 0, $adds = '')
 {
  $number=1;
  $child = $this->get_child($myid);
  if(is_array($child))
  {
      $total = count($child);
   foreach($child as $id=>$a)
   {
    $j=$k='';
    if($number==$total)
    {
     $j .= $this->icon[2];
    }
    else
    {
     $j .= $this->icon[1];
     $k = $adds ? $this->icon[0] : '';
    }
    $spacer = $adds ? $adds.$j : '';
    
    $selected = $this->have($sid,$id) ? 'selected' : '';
    //echo $sid.'=>'.$id.' : '.$selected.' . <br/>';
    @extract($a);
    eval("$nstr = "$str";");
    $this->ret .= $nstr;
    $this->get_tree_multi($id, $str, $sid, $adds.$k.'&nbsp;');
    $number++;
   }
  }
  return $this->ret;
 }
 
 function have($list,$item){
  return(strpos(',,'.$list.',',','.$item.','));
 }
}

php 获取来路[前一页]页面分析函数

本文章提供一款功能全面的获取上一级页面的函数哦,就是来路函数了。

function getref(&$ref,&$fullref) {
  global $err,$conf,$HTTP_GET_VARS,$_GET;

  if(isset($_GET['anr'])) $refer=$_GET['anr'];
  elseif(isset($HTTP_GET_VARS['anr'])) $refer=$HTTP_GET_VARS['anr'];
  else $refer='undefined';
  if(empty($refer)) $refer='undefined';
  if(!strcmp($refer,'null')) $refer='undefined';
  $refer=urldecode($refer);
  $refer=modsec($refer);
  $refer=txtproc($refer);

  //to correct back slashes            http://111cn.netindex
  $refer=str_replace("\","/",$refer);
  //to remove unnecessary points       http://111cn.net.
  $refer=preg_replace("//./",'/',$refer);
  $refer=preg_replace("/.//",'/',$refer);
  $refer=preg_replace("/.*$/",'',$refer);
  $refer=preg_replace("/("|')*$/",'',$refer);
  //to remove unnecessary duplicates of slashes             http://111cn.net///
  $refer=preg_replace("/([^:])(/)+/",'$1/',$refer);
  $fullref=$refer;

  $refer=preg_replace("/^(https?://)(www.)?/i",'',$refer);
  $ref=preg_replace("/[?|&|#|;].*$/i",'',$refer);
  $ref=preg_replace("/(/)*$/",'',$ref);
  $ref=trim($ref);
  $ref=preg_replace("/.*$/",'',$ref);
  $ref=preg_replace("/("|')*$/",'',$ref);
  $ref=trim($ref);

  //check referrer (bad)
  if(empty($ref)) $ref='undefined';
  //search "." in domain name
  if(!preg_match("/^([^./]+.)+([^./])+/i",$ref))  $ref='undefined';
}

}

本款源码是一款php 网站同IP查询代码哦,如果你喜欢就进来看看吧。

<?php
if(function_exists('date_default_timezone_set')){
 date_default_timezone_set('Asia/Shanghai'); //设定时区
}
define("APP_ROOT",dirname(dirname(__FILE__))); //网站根目录

function visitorIP(){ //访问者IP
 if($_SERVER['HTTP_X_FORWARDED_FOR']){
    $ipa = $_SERVER['HTTP_X_FORWARDED_FOR'];
  }elseif($_SERVER['HTTP_CLIENT_IP']){
    $ipa = $_SERVER['HTTP_CLIENT_IP'];
  }else{
    $ipa = $_SERVER['REMOTE_ADDR'];
 }
 return $ipa;
}

function cleanDomain($q,$w=0){ //整理域名 $w=1过滤www.前缀 $w=0不过滤
 $q = htmlspecialchars(strtolower(trim($q)));
 if(substr($q,0,7) == "http://" || substr($q,0,8) == "https://" || substr($q,0,6) == "ftp://"){
  $q = str_replace("http:/","",$q);
  $q = str_replace("https:/","",$q);
  $q = str_replace("ftp:/","",$q);
 }
 if(substr($q,0,4) == "www." && $w==1) {
  $q = str_replace("www.","",$q);
 }
 $q = trim($q,"/");
 return $q;
}

//获取网页
class HTTPRequest
{
/*
获取网页
*/
   var $_fp;        // HTTP socket
   var $_url;        // full URL
   var $_host;        // HTTP host
   var $_protocol;    // protocol (HTTP/HTTPS)
   var $_uri;        // request URI
   var $_port;        // port
  
   // scan url
   function _scan_url()
   {
       $req = $this->_url;
      
       $pos = strpos($req, '://');
       $this->_protocol = strtolower(substr($req, 0, $pos));
      
       $req = substr($req, $pos+3);
       $pos = strpos($req, '/');
       if($pos === false)
           $pos = strlen($req);
       $host = substr($req, 0, $pos);
      
       if(strpos($host, ':') !== false)
       {
           list($this->_host, $this->_port) = explode(':', $host);
       }
       else
       {
           $this->_host = $host;
           $this->_port = ($this->_protocol == 'https') ? 443 : 80;
       }
      
       $this->_uri = substr($req, $pos);
       if($this->_uri == '')
           $this->_uri = '/';
   }
  
   // constructor
   function HTTPRequest($url)
   {
       $this->_url = $url;
       $this->_scan_url();
   }
  
   // download URL to string
   function DownloadToString()
   {
       $crlf = "rn";
       $response="";
       // generate request
       $req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf
           .    'Host: ' . $this->_host . $crlf
           .    $crlf;
      
       // fetch
       $this->_fp = @fsockopen(($this->_protocol == 'https' ? 'ssl://' : '') . $this->_host, $this->_port);
       @fwrite($this->_fp, $req);
       while(is_resource($this->_fp) && $this->_fp && !feof($this->_fp))
           $response .= fread($this->_fp, 1024);
       @fclose($this->_fp);
      
       // split header and body
       $pos = strpos($response, $crlf . $crlf);
       if($pos === false)
           return($response);
       $header = substr($response, 0, $pos);
       $body = substr($response, $pos + 2 * strlen($crlf));
      
       // parse headers
       $headers = array();
       $lines = explode($crlf, $header);
       foreach($lines as $line)
           if(($pos = strpos($line, ':')) !== false)
               $headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));
      
       // redirection?
       if(isset($headers['location']))
       {
           $http = new HTTPRequest($headers['location']);
           return($http->DownloadToString($http));
       }
       else
       {
           return($body);
       }
   }
}

function get_html($siteurl) {
 //将网页代码存入字符串
 $r=new HTTPRequest($siteurl);
 $htm=$r->DownloadToString();
 return $htm;
}

$visitorip = visitorIP();

$q = cleanDomain($_POST['q']);
$q_encode = urlencode($q);

$title = "同IP站点查询";

$chaxun_status = 0; //查询状态 -1是没有查询参数,0是查询出错,1是查域名,2是查IP

if(isset($_GET['action']) && trim($_GET['action']) == "do"){ //AJAX调出数据
 $ipArr = ReverseIP($q);
 if(count($ipArr)>0){
  echo '<p class="f14">在此IP找到了'.count($ipArr).'个域名,见下:</p>';
  echo '<ul class="lst">';
  for($i=0;$i<count($ipArr);$i++){
   echo '<li><a href="http://'.$ipArr[$i].'/" title="访问 '.$ipArr[$i].'" target="_blank" class="f14 l200">'.$ipArr[$i].'</a></li>';
  }
  echo '</ul><div class="cboth"></div>';
 }else{
  echo '<p class="f14">没有找到IP '.$ip.' 对应的域名记录!</p>';
 }
 die();
}

function IpToInt($Ip){ //IP转为数字
    $array=explode('.',$Ip);
    $Int=($array[0] * 256*256*256) + ($array[1]*256*256) + ($array[2]*256) + $array[3];
    return $Int;
}

function ReverseIP($q){
 $htm = get_html('http://www.ip-adress.com/reverse_ip/'.$q);
 preg_match_all('/<a href="/whois/(.*)">Whois</a>/', $htm, $tt);
 $res = $tt[1];
 return $res;
}

if(preg_match("/[a-zA-Z-_]+/si",$q)){ //如果查询的是域名
 $ip = gethostbyname($q);
 if($ip == $q){
  $ip = $visitorip;
  $chaxun_status = -1;
 }else{
  $chaxun_status = 1;
 }
}elseif(ereg("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$",$q)){ //如果查询的是IP
 $ip = $q;
 $chaxun_status = 2;
}else{
 $ip = $visitorip;
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>同IP站点查询</title>
<style>
*{margin:0;padding:0;}
body{font-size:12px;font-family: Geneva, Arial, Helvetica, sans-serif;}
a img {border:0;}

.red{color:#f00;}
.center{text-align:center;}
p{padding:5px 0 6px 0;word-break:break-all;word-wrap:break-word;}
.f14{font-size:14px;}
a,a:visited{color:#0353ce;}
table {font-size:12px;}
 table th {font-size:12px;font-weight:bold;background-color:#f7f7f7;line-height:200%;padding: 0 5px;}
 table th {font-size:12px;font-weight:bold;background:#EDF7FF;padding: 0 5px;color:#014198;line-height:200%;}
.red{color:red}
.blue{color:blue}
#footer{line-height:150%;text-align:center;color:#9c9c9c;padding: 8px 0;}
 #footer a,#footer a:visited{color:#9c9c9c;}
ul.lst{padding:0;margin:0;width:100%;}
 ul.lst li{list-style-type:none;float:left;padding:0 0 0 12px;line-height:24px;height:24px;overflow:hidden;}
 ul.lst li{width:258px!important;width:270px;}
</style>
<? if($chaxun_status>0){ ?>
<SCRIPT type="text/javascript">
<!--
 var xmlHttp;
 function creatXMLHttpRequest() {
  if(window.ActiveXObject) {
   xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
  } else if(window.XMLHttpRequest) {
   xmlHttp = new XMLHttpRequest();
  }
 }

 function startRequest() {
  var queryString;
  var domain = "<?=$ip?>";
  queryString = "q=" + domain;
  creatXMLHttpRequest();
  xmlHttp.open("POST","./?action=do","true");
  xmlHttp.onreadystatechange = handleStateChange;
  xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
  xmlHttp.send(queryString);
 }

 function handleStateChange() {
  if(xmlHttp.readyState == 1) {
   document.getElementById('ipresult').style.cssText = "";
   document.getElementById('ipresult').innerHTML = '<span class="green">结果加载中,请稍等...</span>';
  }
  if(xmlHttp.readyState == 4) {
   if(xmlHttp.status == 200) {
    document.getElementById('ipresult').style.cssText = "";
    var allcon =  xmlHttp.responseText;
    document.getElementById('ipresult').innerHTML = allcon;
   }
  }
 }
 
//-->
</SCRIPT>
<? } ?>
</head>

<body>
<div align="center">
<table cellspacing="4" cellpadding="0" style="background-color:#f7f7f7;border-bottom:1px solid #dfdfdf;" width="778">
<tr>
  <td align="left"><a href="/" target="_blank">站长工具</a> &gt; <a href="./" target="_blank">同IP站点查询</a></td>
  <td align="right"><a href="javascript:;" onClick="window.external.AddFavorite(document.location.href,document.title);">收藏本页</a></td></tr></table>
<div id="result"><br />
<table width="700" cellpadding="2" cellspacing="0" style="border:1px solid #B2D0EA;">
<tr>
<th align="left"><a href="./" target="_blank">同IP站点查询</a></th>
</tr>
<tr><td align="center">
<table border="0" cellPadding="0" cellSpacing="1">
<tr><td style="font-size:14px">
<br />
<form action="" method="post" name="f1">IP地址或域名 <input name="q" id="q" type="text" size="18" delay="0" value="<? if($chaxun_status>0) echo $q; ?>" style="width:200px;height:22px;font-size:16px;font-family: Geneva, Arial, Helvetica, sans-serif;" /> <input type="submit" value=" 查询 " /></form>
</td></tr></table><br />
</td></tr>
<tr><td align="center" valign="middle" height="40" style="font-size:12px">输入域名或者IP地址,查询同一IP地址的服务器上有哪些网站。</td></tr>
</table>
<br />
<table width="700" cellpadding=2 cellspacing=0 style="border:1px solid #B2D0EA;">
<tr>
<th align="left"><?
 if($chaxun_status==1){
  echo '<a href="./">'.$title.'</a> &gt; 域名: '.$q;
 }elseif($chaxun_status==2){
  echo '<a href="./">'.$title.'</a> &gt; IP: '.$ip;
 }else{
  echo $title;
 }
?></th>
</tr>
<tr><td align="left">
<div style="padding:20px">
<p class="f14">
<?
 if(!$q){
  $ipq = '您的IP地址是:<span class="blue f14">'.$ip.'</span>';
 }elseif($chaxun_status == 0){
  $ipq = '<b class="red f14">出错啦!</b>没有找到与 <b class="blue f14">'.$q.'</b> 匹配的结果,请确定IP/域名的格式是否写对!</p><p class="f14 blue">你的IP地址是:'.$ip;
 }elseif($chaxun_status==1){
  $ipq = '你查询的域名 <span class="blue f14">'.$q.'</span></p><p class="f14">域名的IP: <span class="blue f14">'.$ip.'</span>';
 }else{
  $ipq = "你查询的IP:".$ip;
 }
 echo $ipq;
 ?></p><? if($chaxun_status>0){ ?>
 <div id="ipresult"></div><script>startRequest();</script>
<? } ?></p><hr style="border-style: dotted;" color="#cccccc" size="1" /><p align="center">相关查询: <A href="../alexa">Alexa查询</A> | <A href="../domain/">域名注册查询</A> | <A href="../whois">Whois查询</A> | <A href="../ip/">IP地址查询</A> | <A href="../pr/pr.php">PR查询</A> | <A href="../weath/">天气预报查询</A> | <A href="../robot">模仿蜘蛛</A> | <A href="/index.php">友情链接查询</A></p>
</div>
</td></tr>
</table><br />
</div>
</div>
<div id="footer">&copy; 2009 <a href="http://tool.111cn.net/">站长工具</a></div>
<div style="display:none;"></div>
</body>
</html>

同IP查询代码下载包

这是一款可以同时上传10个文件的php+ajax无刷新的上传源码了,并且还带有上传进度条的哦,好了费话不说多了喜欢就来下载吧。

<!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=gb2312" />
<title>无刷新文件上传系统</title>
</head>
<body>
<style>
.fu_list {
 width:600px;
 background:#ebebeb;
 font-size:12px;
}
.fu_list td {
 padding:5px;
 line-height:20px;
 background-color:#fff;
}
.fu_list table {
 width:100%;
 border:1px solid #ebebeb;
}
.fu_list thead td {
 background-color:#f4f4f4;
}
.fu_list b {
 font-size:14px;
}
/*file容器样式*/
a.files {
 width:90px;
 height:30px;
 overflow:hidden;
 display:block;
 border:1px solid #BEBEBE;
 background:url(img/fu_btn.gif) left top no-repeat;
 text-decoration:none;
}
a.files:hover {
 background-color:#FFFFEE;
 background-position:0 -30px;
}
/*file设为透明,并覆盖整个触发面*/
a.files input {
 margin-left:-350px;
 font-size:30px;
 cursor:pointer;
 filter:alpha(opacity=0);
 opacity:0;
}
/*取消点击时的虚线框*/
a.files, a.files input {
 outline:none;/*ff*/
 hide-focus:expression(this.hideFocus=true);/*ie*/
}
</style>
<form id="uploadForm" action="File.php">
  <table border="0" cellspacing="1" class="fu_list">
    <thead>
      <tr>
        <td colspan="2"><b>上传文件</b></td>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td align="right" width="15%" style="line-height:35px;">添加文件:</td>
        <td><a href="javascript:void(0);" class="files" id="idFile"></a> <img id="idProcess" style="display:none;" src="img/loading.gif" /></td>
      </tr>
      <tr>
        <td colspan="2"><table border="0" cellspacing="0">
            <thead>
              <tr>
                <td>文件路径</td>
                <td width="100"></td>
              </tr>
            </thead>
            <tbody id="idFileList">
            </tbody>
          </table></td>
      </tr>
      <tr>
        <td colspan="2" style="color:gray">温馨提示:最多可同时上传 <b id="idLimit"></b> 个文件,只允许上传 <b id="idExt"></b> 文件。 </td>
      </tr>
      <tr>
        <td colspan="2" align="center" id="idMsg"><input type="button" value="开始上传" id="idBtnupload" disabled="disabled" />
          &nbsp;&nbsp;&nbsp;
          <input type="button" value="全部取消" id="idBtndel" disabled="disabled" />
        </td>
      </tr>
    </tbody>
  </table>
</form>
<script type="text/javascript">

var isIE = (document.all) ? true : false;

var $ = function (id) {
    return "string" == typeof id ? document.getElementById(id) : id;
};

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Extend = function(destination, source) {
 for (var property in source) {
  destination[property] = source[property];
 }
}

var Bind = function(object, fun) {
 return function() {
  return fun.apply(object, arguments);
 }
}

var Each = function(list, fun){
 for (var i = 0, len = list.length; i < len; i++) { fun(list[i], i); }
};

//文件上传类
var FileUpload = Class.create();
FileUpload.prototype = {
  //表单对象,文件控件存放空间
  initialize: function(form, folder, options) {
 
 this.Form = $(form);//表单
 this.Folder = $(folder);//文件控件存放空间
 this.Files = [];//文件集合
 
 this.SetOptions(options);
 
 this.FileName = this.options.FileName;
 this._FrameName = this.options.FrameName;
 this.Limit = this.options.Limit;
 this.Distinct = !!this.options.Distinct;
 this.ExtIn = this.options.ExtIn;
 this.ExtOut = this.options.ExtOut;
 
 this.onIniFile = this.options.onIniFile;
 this.onEmpty = this.options.onEmpty;
 this.onNotExtIn = this.options.onNotExtIn;
 this.onExtOut = this.options.onExtOut;
 this.onLimite = this.options.onLimite;
 this.onSame = this.options.onSame;
 this.onFail = this.options.onFail;
 this.onIni = this.options.onIni;
 
 if(!this._FrameName){
  //为每个实例创建不同的iframe
  this._FrameName = "uploadFrame_" + Math.floor(Math.random() * 1000);
  //ie不能修改iframe的name
  var oFrame = isIE ? document.createElement("<iframe name="" + this._FrameName + "">") : document.createElement("iframe");
  //为ff设置name
  oFrame.name = this._FrameName;
  oFrame.style.display = "none";
  //在ie文档未加载完用appendChild会报错
  document.body.insertBefore(oFrame, document.body.childNodes[0]);
 }
 
 //设置form属性,关键是target要指向iframe
 this.Form.target = this._FrameName;
 this.Form.method = "post";
 //注意ie的form没有enctype属性,要用encoding
 this.Form.encoding = "multipart/form-data";

 //整理一次
 this.Ini();
  },
  //设置默认属性
  SetOptions: function(options) {
    this.options = {//默认值
  FileName: "Files[]",//文件上传控件的name,配合后台使用
  FrameName: "",//iframe的name,要自定义iframe的话这里设置name
  onIniFile: function(){},//整理文件时执行(其中参数是file对象)
  onEmpty: function(){},//文件空值时执行
  Limit:  10,//文件数限制,0为不限制
  onLimite: function(){},//超过文件数限制时执行
  Distinct: true,//是否不允许相同文件
  onSame:  function(){},//有相同文件时执行
  ExtIn:  ["gif","jpg","rar","zip","iso","swf","exe"],//允许后缀名
  onNotExtIn: function(){},//不是允许后缀名时执行
  ExtOut:  [],//禁止后缀名,当设置了ExtIn则ExtOut无效
  onExtOut: function(){},//是禁止后缀名时执行
  onFail:  function(){},//文件不通过检测时执行(其中参数是file对象)
  onIni:  function(){}//重置时执行
    };
    Extend(this.options, options || {});
  },
  //整理空间
  Ini: function() {
 //整理文件集合
 this.Files = [];
 //整理文件空间,把有值的file放入文件集合
 Each(this.Folder.getElementsByTagName("input"), Bind(this, function(o){
  if(o.type == "file"){ o.value && this.Files.push(o); this.onIniFile(o); }
 }))
 //插入一个新的file
 var file = document.createElement("input");
 file.name = this.FileName; file.type = "file"; file.onchange = Bind(this, function(){ this.Check(file); this.Ini(); });
 this.Folder.appendChild(file);
 //执行附加程序
 this.onIni();
  },
  //检测file对象
  Check: function(file) {
 //检测变量
 var bCheck = true;
 //空值、文件数限制、后缀名、相同文件检测
 if(!file.value){
  bCheck = false; this.onEmpty();
 } else if(this.Limit && this.Files.length >= this.Limit){
  bCheck = false; this.onLimite();
 } else if(!!this.ExtIn.length && !RegExp(".(" + this.ExtIn.join("|") + ")$", "i").test(file.value)){
  //检测是否允许后缀名
  bCheck = false; this.onNotExtIn();
 } else if(!!this.ExtOut.length && RegExp(".(" + this.ExtOut.join("|") + ")$", "i").test(file.value)) {
  //检测是否禁止后缀名
  bCheck = false; this.onExtOut();
 } else if(!!this.Distinct) {
  Each(this.Files, function(o){ if(o.value == file.value){ bCheck = false; } })
  if(!bCheck){ this.onSame(); }
 }
 //没有通过检测
 !bCheck && this.onFail(file);
  },
  //删除指定file
  Delete: function(file) {
 //移除指定file
 this.Folder.removeChild(file); this.Ini();
  },
  //删除全部file
  Clear: function() {
 //清空文件空间
 Each(this.Files, Bind(this, function(o){ this.Folder.removeChild(o); })); this.Ini();
  }
}

var fu = new FileUpload("uploadForm", "idFile", { ExtIn: ["gif","jpg"],
 onIniFile: function(file){ file.value ? file.style.display = "none" : this.Folder.removeChild(file); },
 onEmpty: function(){ alert("请选择一个文件"); },
 onLimite: function(){ alert("超过上传限制"); },
 onSame: function(){ alert("已经有相同文件"); },
 onNotExtIn: function(){ alert("只允许上传" + this.ExtIn.join(",") + "文件"); },
 onFail: function(file){ this.Folder.removeChild(file); },
 onIni: function(){
  //显示文件列表
  var arrRows = [];
  if(this.Files.length){
   var oThis = this;
   Each(this.Files, function(o){
    var a = document.createElement("a"); a.innerHTML = "取消"; a.href = "javascript:void(0);";
    a.onclick = function(){ oThis.Delete(o); return false; };
    arrRows.push([o.value, a]);
   });
  } else { arrRows.push(["<font color='gray'>没有添加文件</font>", "&nbsp;"]); }
  AddList(arrRows);
  //设置按钮
  $("idBtnupload").disabled = $("idBtndel").disabled = this.Files.length <= 0;
 }
});

$("idBtnupload").onclick = function(){
 //显示文件列表
 var arrRows = [];
 Each(fu.Files, function(o){ arrRows.push([o.value, "&nbsp;"]); });
 AddList(arrRows);
 
 fu.Folder.style.display = "none";
 $("idProcess").style.display = "";
 $("idMsg").innerHTML = "正在添加文件到您的网盘中,请稍候……<br />有可能因为网络问题,出现程序长时间无响应,请点击“<a href='?'><font color='red'>取消</font></a>”重新上传文件";
 
 fu.Form.submit();
}

//用来添加文件列表的函数
function AddList(rows){
 //根据数组来添加列表
 var FileList = $("idFileList"), oFragment = document.createDocumentFragment();
 //用文档碎片保存列表
 Each(rows, function(cells){
  var row = document.createElement("tr");
  Each(cells, function(o){
   var cell = document.createElement("td");
   if(typeof o == "string"){ cell.innerHTML = o; }else{ cell.appendChild(o); }
   row.appendChild(cell);
  });
  oFragment.appendChild(row);
 })
 //ie的table不支持innerHTML所以这样清空table
 while(FileList.hasChildNodes()){ FileList.removeChild(FileList.firstChild); }
 FileList.appendChild(oFragment);
}


$("idLimit").innerHTML = fu.Limit;

$("idExt").innerHTML = fu.ExtIn.join(",");

$("idBtndel").onclick = function(){ fu.Clear(); }

//在后台通过window.parent来访问主页面的函数
function Finish(msg){ alert(msg); location.href = location.href; }

</script>
</body>
</html>

file.php文件上传的php源码。


<!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=gb2312" />
<title>无标题文档</title>
</head>
<body>
<?
$sort=12;
$f_type=strtolower("swf,jpg,rar,zip,7z,iso,gif");//设置可上传的文件类型
$file_size_max=200*1024*1024;//限制单个文件上传最大容量
$overwrite = 0;//是否允许覆盖相同文件,1:允许,0:不允许
$f_input="Files";//设置上传域名称
    foreach($_FILES[$f_input]["error"] as $key => $error){
        $up_error="no";
        if ($error == UPLOAD_ERR_OK){
            $f_name=$_FILES[$f_input]['name'][$key];//获取上传源文件名
   
            $uploadfile=$uploaddir.strtolower(basename($f_name));
            
            $tmp_type=substr(strrchr($f_name,"."),1);//获取文件扩展名
   $tmp_type=strtolower($tmp_type);
            if(!stristr($f_type,$tmp_type)){
                echo "<script>alert('对不起,不能上传".$tmp_type."格式文件, ".$f_name." 文件上传失败!')</script>";
                $up_error="yes";
            }
            
            if ($_FILES[$f_input]['size'][$key]>$file_size_max) {
   
                echo "<script>alert('对不起,你上传的文件 ".$f_name." 容量为".round($_FILES[$f_input]
['size'][$key]/1024)."Kb,大于规定的".($file_size_max/1024)."Kb,上传失败!')</script>";
                $up_error="yes";
            }
            
            if (file_exists($uploadfile)&&!$overwrite){
                echo "<script>alert('对不起,文件 ".$f_name." 已经存在,上传失败!')</script>";
                $up_error="yes";
            }
             $string = 'abcdefghijklmnopgrstuvwxyz0123456789';
$rand = '';
for ($x=0;$x<12;$x++)
  $rand .= substr($string,mt_rand(0,strlen($string)-1),1);
$t=date("ymdHis").substr($gettime[0],2,6).$rand;
$attdir="./file/"; 
    if(!is_dir($attdir))  
    {  mkdir($attdir);}
            $uploadfile=$attdir.$t.".".$tmp_type;
            if(($up_error!="yes") and (move_uploaded_file($_FILES[$f_input]['tmp_name']

[$key], $uploadfile))){

                
    $_msg=$_msg.$f_name.'上传成功n';
    
    
            }
   else{
   $_msg=$_msg.$f_name.'上传失败n';
   }
        }
 
    }
echo "<script>window.parent.Finish('".$_msg."');</script>"; 
?>
</body>
</html>

效果图

[!--infotagslink--]

相关文章

  • Php文件上传类class.upload.php用法示例

    本文章来人大家介绍一个php文件上传类的使用方法,期望此实例对各位php入门者会有不小帮助哦。 简介 Class.upload.php是用于管理上传文件的php文件上传类, 它可以帮...2016-11-25
  • PHP swfupload图片上传的实例代码

    PHP代码如下:复制代码 代码如下:if (isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) { $upload_file = $_FILES['Filedata']; $fil...2013-10-04
  • 百度编辑器ueditor修改图片上传默认路径

    本案例非通用,仅作笔记以备用 修改后的结果是 百度编辑器里上传的图片路径为/d/file/upload1...2014-07-03
  • 适用于初学者的简易PHP文件上传类

    本文实例讲述了PHP多文件上传类,分享给大家供大家参考。具体如下:<&#63;phpclass Test_Upload{ protected $_uploaded = array(); protected $_destination; protected $_max = 1024000; protected $_messages =...2015-10-30
  • Java实现将图片上传到webapp路径下 路径获取方式

    这篇文章主要介绍了Java实现将图片上传到webapp路径下 路径获取方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-11-12
  • php+js实现异步图片上传实例分享

    upload.php复制代码 代码如下:<?phpif(isset($_FILES["myfile"])){$ret = array();$uploadDir = 'images'.DIRECTORY_SEPARATOR.date("Ymd").DIRECTORY_SEPARATOR;$dir = dirname(__FILE__).DIRECTORY_SEPARATOR.$upl...2014-06-07
  • ASP.NET百度Ueditor编辑器实现上传图片添加水印效果

    这篇文章主要给大家介绍了ASP.NET百度Ueditor编辑器1.4.3这个版本实现上传图片添加水印效果的相关资料,文中通过图文及示例代码介绍的非常详细,相信对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。...2021-09-22
  • 利用Yii框架实现图片上传

    这篇文章主要介绍了Yii框架实现图片上传的方法,结合实例形式较为详细的分析了Yii框架实现图片上传功能的具体步骤与相关操作技巧,需要的朋友可以参考下 本文实例...2017-07-06
  • php文件上传(强大文件图片上传类)

    这款文件上传实用代码,可以方便的上传你指定的文件或图片,同时也可以快速的限制上传图片文件类或大小。 /* * created on 2010-6-21 * * the class for image...2016-11-25
  • php多文件上传 多图片上传程序代码

    多文件上传其实就包括了图片及各种文件了,下面介绍的是一款PHP多文件上传类,一共两个文件,upp.php 和 uploadFile.php,upp.php,这是前台所显示的表单文件了,默认的是四个...2016-11-25
  • php 图片上传代码(具有生成缩略图与增加水印功能)

    这款图片上传源代码是一款可以上传图片并且还具有给上传的图片生成缩略图与增加水印功能哦,可以说是一款完美的图片上传类哦。 代码如下 复制代码 ...2016-11-25
  • php图片上传类,支持加水印,生成略缩图

    分享一个网友写的php图片上传类,支持加水印,生成略缩图功能哦,面是配置和可以获取的一些信息(每一个配置信息都有默认值,如无特殊需要,可以不配置): 代码如下 ...2016-11-25
  • php实现多图片上传程序代码

    php实现多图片上传方法非常的简单只要遍历数组然后使用上传函数就可以搞定了,可以说几句代码就可以实现,但对于新手来讲还是有点,下面一起来看看。 在做图片上传时用...2016-11-25
  • php 图片上传代码例子

    下面来为你免费提供一款php 图片上传代码哦,如果你正在找文件上传的图片代码就进来看看吧,这是一款只支持jpg,gif,png,swf文件上传的php实例代码 <?php 代...2016-11-25
  • php 图片上传加水印(自动增加水印)

    这是一款完美的php文件上传代码,图片上传成功后并自动给图片增加上水印,这样很好的快速的提高的了要手工一张张增加水印效果。 代码如下 复制代码 ...2016-11-25
  • php discuz chhome 图片上传swfupload功能

    php discuz chhome 图片上传swfupload功能 这上传与discuz来比, 还相差太远. 功能也欠缺. 除了部分内置的url引向,我们改不了之外, 其它的数据都是可以修改的. <?...2016-11-25
  • php图片上传并生成水印

    php图片上传并生成水印 <?php header('Content-Type:text/html;charset=gb2312'); $animation = new Imagick(); $animation->setFormat(...2016-11-25
  • 自己写的一个PHP上传类

    主要功能: 文件上传,获取文件名,获取文件大小,随机生成新文件名,获取文件类型,图片生成缩略图,返回缩略图文件名,返回上传后生成的文件的文件名,返回上传后的文件路径 class...2016-11-25
  • PHP中Ckeditor+Ckfinder配置图片上传功能

    从标题来看我们知道Ckeditor不支持图片上传功能,它是需要一个组件Ckfinder才可以支持上传图片, 本文章就来详细的介绍了如何配置Ckeditor+Ckfinder实现图片上传的功能...2016-11-25
  • asp.net图片上传实例

    网站后台都需要有上传图片的功能,下面的例子就是实现有关图片上传。缺点:图片上传到本服务器上,不适合大量图片上传...2021-09-22