加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

php+js/ajax 实现多图片或文件无刷新上传

(2015-08-18 14:44:02)
标签:

php

js

juery.form

phpajax实现无刷新上

无刷新上传多文件/图

分类: 伏羲夜笔--php
效果图:
http://s8/mw690/00348ltKty6UJiGtMzR27&690实现多图片或文件无刷新上传" TITLE="php+js/ajax 实现多图片或文件无刷新上传" />

功能介绍:
1、可以实现单图片/文件上传
2、可以实现多图片/文件上传
3、可以获取文件上传的错误信息
4、可以获取上传后文件的名称
5、可以在实例化时,实例 上传文件路径、只能上传指定文件类型、设置文件最大kb

代码如下:

1、目录结构,自己看着写:如图
http://s13/mw690/00348ltKty6UJjiIxaIbc&690实现多图片或文件无刷新上传" TITLE="php+js/ajax 实现多图片或文件无刷新上传" />
具体代码:

index.html

<html>
<head>
<title>多图片或文件上传</title>
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.form.min.js"></script>
<script type="text/javascript" src="myjs.js"></script>
</head>
<body>
<form class="form-horizontal" role="form" id="postform" name="postform">
    <label> 附加上传 </label>
    <div style="margin-bottom:20px;">
        <input type="button" value="增加上传控件"  onclick="additem('tb')" id="addFile" class="hide" style="height: 30px;">
        <table cellspacing="1" id="tb" style="width:400px; padding:0; margin:0">
        </table>
    </div>
    <input type="button" value="多图片/文件上传" id="up" />
</form>
</body>
</html>


myjs.js

$(function(){
    $("#up").click(function(){
        $('#postform').ajaxSubmit({
            async : false,
            type : "POST",
            url : "do.php?action=upFile",
            data : {},
            dataType : "json",
            success :  function(data) {
                if(data==''){
                    alert("上传文件失败");return false;   
                }
                if(data.status!=''){//上传失败,显示错误信息
                    alert(data.status);return false;   
                }
                alert("上传成功。上传文件名:"+data.fileName);//得到文件名就可以随意操作了,如显示等操作
               
            }
        });                       
    });          
})

//全局变量,代表文件域的个数,并用该变量区分文件域的name属性
var file_count = 1;
//增加文件 域  
function additem(id,url,amId) {
    //定义行变量row;单元格变量cell;单元格内容变量str。
    var row,cell,str;
    //在指定id的table中插入一行
    row = eval_r("document.all["+'"'+id+'"'+"]").insertRow();
    if(row != null ) {
        //设置行的背景颜色
        row.bgColor="white";
        row.height="50";
        //在行中插入单元格
        cell = row.insertCell();
        //设置str的值,包括一个文件域和一个删除按钮
        str='<div><input onselectstart="return false" class="tf" onpaste="return false" type="file"  name="file[]" style="width:330px;display:inline;" onkeydown="return false;"/>';
        str += " <input type="+'"'+"button"+'"'+" value="+'"'+"删除"+'"'+"   onclick='deleteitem(this,"+'"'+"tb"+'"'+");' style='display:inline;'></div>";
       
        if(url!=undefined){
            //str += '图片:<img src="'+url+'" height="30" width="30" name="showImg" id="'+amId+'">';
            str +='文件:<span name="showImg" id="'+amId+'">'+url+'</span>';
        }
        //文件域个数增加
        file_count++;
        //设置单元格的innerHTML为str的内容
        cell.innerHTML=str;
    }
}
//删除文件域
function deleteitem(obj,id) {
    $(obj).parent().parent().parent().remove();
}


do.php

include "FileUpload.class.php";
    $action = $_GET['action'];
    $array = '';
    switch($action){
        case "upFile":
            if(isset($_FILES)){
                $uploadFileObject = new FileUpload();
                $uploadFileObject->path = "upload";//文件存放目录
                $uploadFileObject->allowtype = array('jpg','gif','png','jpeg');//可以不设置,类中有默认类型
                $uploadFileObject->maxsize = "100000000";//可以不设置,类中有默认
                $uploadFileObject->upload("file");
                $returnStatus = $uploadFileObject->getErrorMsg();
                if(empty($returnStatus)){//returnStatus错误信息数据
                    //成功
                    $fileName = $uploadFileObject->getFileName();
                    $array = array(
                        "status"=>$returnStatus,
                        "fileName"=>$fileName,
                    );
                    $array = json_encode($array);
                }
            }
            echo $array;
        break;
   
    }



fileupload.class.php


  class FileUpload {
    public $path = "uploade";          //上传文件保存的路径
    public $allowtype = array('jpg','gif','png','jpeg'); //设置限制上传文件的类型
    public $maxsize = 1000000;           //限制文件上传大小(字节)
    private $israndname = true;           //设置是否随机重命名文件, false不随机
 
    private $originName;              //源文件名
    private $tmpFileName;              //临时文件名
    private $fileType;               //文件类型(文件后缀)
    private $fileSize;               //文件大小
    private $newFileName;              //新文件名
    private $errorNum = 0;             //错误号
    private $errorMess="";             //错误报告消息

   
    function __construct(){
        $this->path = $path;   
        $this->allowtype = $allowtype;
        $this->maxsize = $maxsize;
    }
     
    function set($key, $val){
      $key = strtolower($key);
      if( array_key_exists( $key, get_class_vars(get_class($this) ) ) ){
        $this->setOption($key, $val);
      }
      return $this;
    }
 
   
 
    function upload($fileField,$path='') {
      $return = true;
     
      if( !$this->checkFilePath() ) {      
        $this->errorMess = $this->getError();
        return false;
      }
     
      $name = $_FILES[$fileField]['name'];
      $tmp_name = $_FILES[$fileField]['tmp_name'];
      $size = $_FILES[$fileField]['size'];
      $error = $_FILES[$fileField]['error'];
 
     
      if(is_Array($name)){   
        $errors=array();
       
        for($i = 0; $i < count($name); $i++){
         
          if($this->setFiles($name[$i],$tmp_name[$i],$size[$i],$error[$i] )) {
            if(!$this->checkFileSize() || !$this->checkFileType()){
              $errors[] = $this->getError();
              $return=false;
            }
          }else{
            $errors[] = $this->getError();
            $return=false;
          }
         
          if(!$return)         
            $this->setFiles();
        }
        if($return){
         
          $fileNames = array();     
         
          for($i = 0; $i < count($name); $i++){
            if($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i] )) {
              $this->setNewFileName();
              if(!$this->copyFile()){
                $errors[] = $this->getError();
                $return = false;
              }
              $fileNames[] = $this->newFileName; 
                   
          }
          $this->newFileName = $fileNames;
        }
        $this->errorMess = $errors;
        return $return;
     
      } else {
       
        if($this->setFiles($name,$tmp_name,$size,$error)) {
         
          if($this->checkFileSize() && $this->checkFileType()){
           
            $this->setNewFileName();
           
            if($this->copyFile()){
              return true;
            }else{
              $return=false;
            }
          }else{
            $return=false;
          }
        } else {
          $return=false;
        }
        //如果$return为false, 则出错,将错误信息保存在属性errorMess中
        if(!$return)
          $this->errorMess=$this->getError(); 
 
        return $return;
      }
    }
 
   
    public function getFileName(){
      return $this->newFileName;
    }
    //获取原文件名
    public function getFileOldName(){
      return $this->originName;
    }
 
   
    public function getErrorMsg(){
      return $this->errorMess;
    }
 
   
    private function getError() {
      $str = "上传文件{$this->originName}
<</font>/font>时出错 : ";
      switch ($this->errorNum) {
        case 4: $str .= "没有文件被上传"; break;
        case 3: $str .= "文件只有部分被上传"; break;
        case 2: $str .= "上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值"; break;
        case 1: $str .= "上传的文件超过了php.ini中upload_max_filesize选项限制的值"; break;
        case -1: $str .= "未允许类型"; break;
        case -2: $str .= "文件过大,上传的文件不能超过{$this->maxsize}个字节"; break;
        case -3: $str .= "上传失败"; break;
        case -4: $str .= "建立存放上传文件目录失败,请重新指定上传目录"; break;
        case -5: $str .= "必须指定上传文件的路径"; break;
        default: $str .= "未知错误";
      }
      return $str.'
';
    }
 
   
    private function setFiles($name="", $tmp_name="", $size=0, $error=0) {
      $this->setOption('errorNum', $error);
      if($error)
        return false;
      $this->setOption('originName', $name);
      $this->setOption('tmpFileName',$tmp_name);
      $aryStr = explode(".", $name);
      $this->setOption('fileType', strtolower($aryStr[count($aryStr)-1]));
      $this->setOption('fileSize', $size);
      return true;
    }
 
   
    private function setOption($key, $val) {
      $this->$key = $val;
    }
 
   
    private function setNewFileName() {
      if ($this->israndname) {
        $this->setOption('newFileName', $this->proRandName()); 
      } else{
        $this->setOption('newFileName', $this->originName);
      }
    }
 
   
    private function checkFileType() {
      if (in_array(strtolower($this->fileType), $this->allowtype)) {
        return true;
      }else {
        $this->setOption('errorNum', -1);
        return false;
      }
    }
 
   
    private function checkFileSize() {
      if ($this->fileSize > $this->maxsize) {
        $this->setOption('errorNum', -2);
        return false;
      }else{
        return true;
      }
    }
 
   
    private function checkFilePath() {
      if(empty($this->path)){
        $this->setOption('errorNum', -5);
        return false;
      }
     
      if (!file_exists($this->path) || !is_writable($this->path)) {
        if (!@mkdir($this->path, 0755)) {
          $this->setOption('errorNum', -4);
          return false;
        }
      }
      return true;
    }
 
   
    private function proRandName() {   
      $fileName = date('YmdHis')."_".rand(100,999);   
      return $fileName.'.'.$this->fileType;
    }
 
   
    private function copyFile() {
      if(!$this->errorNum) {
        $path = rtrim($this->path, '/').'/';
        $path .= $this->newFileName;
        if (@move_uploaded_file($this->tmpFileName, $path)) {
          return true;
        }else{
          $this->setOption('errorNum', -3);
          return false;
        }
      } else {
        return false;
      }
    }
  }

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有