服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - PHP实现多图上传(结合uploadify插件)思路分析

PHP实现多图上传(结合uploadify插件)思路分析

2021-03-31 15:33牛逼的霍啸林 PHP教程

这篇文章主要介绍了PHP实现多图上传的方法,实例分析了php结合uploadify插件实现多图上传的具体步骤与相关操作技巧,需要的朋友可以参考下

本文实例讲述了php实现多图上传的方法。分享给大家供大家参考,具体如下:

PHP实现多图上传(结合uploadify插件)思路分析

PHP实现多图上传(结合uploadify插件)思路分析

1.已有图片可以删除
2.有一个新增的按钮
3.点击新增按钮,跳出frame框
4.在frame框中实现图片异步上传与及时效果
5.上传成功后,调用回调函数
6.弹出框中的图片可以进行删除
7.frame弹出框点击保存,把图片通过js展示到页面中
8.页面点击保存,把图片数据保存到数据库

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
foreach($info['product_img'] as $product_img)
{
?>
  <div style="width:100px; text-align:center; margin: 5px; display:inline-block;" class="goods_xc">
    <input type="hidden" value="<?php echo $product_img['img'];?>" name="product_img[]">
    <a onclick="" href="<?php echo $product_img['img'];?>" target="_blank"><img width="100" height="100" src="<?php echo $product_img['img'];?>"></a>
    <br>
    <a href="javascript:void(0)" onclick="clearpicarr2(this,'<?php echo $product_img['img'];?>')">删除</a>
  </div>
<?php
}
?>
<div class="goods_xc" style="width:100px; text-align:center; margin: 5px; display:inline-block;">
  <input type="hidden" name="product_img[]" />
  <a href="javascript:void(0);" onclick="getuploadify(10,'','product','call_back2');"><img src="<?php echo img_path?>add-button.jpg" width="100" height="100" /></a>
  <br/>
  <a href="javascript:void(0)">  </a>
</div>

点评:点击的时候,调用getuploadify方法。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * 上传图片 后台专用
 * @access public
 * @null int 一次上传图片张图
 * @elementid string 上传成功后返回路径插入指定id元素内
 * @path string 指定上传保存文件夹,默认存在public/upload/temp/目录
 * @callback string 回调函数(单张图片返回保存路径字符串,多张则为路径数组 )
 */
function getuploadify(num,elementid,path,callback)
  var pc_hash = $('#pc_hash').val();
  var upurl ='?m=admin&c=upload&a=upload&num='+num+'&input='+elementid+'&path='+path+'&func='+callback+'&pc_hash='+pc_hash;
  var iframe_str='<iframe frameborder="0" ';
  iframe_str=iframe_str+'id=uploadify ';    
  iframe_str=iframe_str+' src='+upurl;
  iframe_str=iframe_str+' allowtransparency="true" class="uploadframe" scrolling="no"> ';
  iframe_str=iframe_str+'</iframe>';        
  $("body").append(iframe_str); 
  $("iframe.uploadframe").css("height",$(document).height()).css("width","100%").css("position","absolute").css("left","0px").css("top","0px").css("z-index","999999").show();
  $(window).resize(function(){
    $("iframe.uploadframe").css("height",$(document).height()).show();
  });
}

点评:生成一个iframe框。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public function upload(){
    $func = $_request['func'];
    $path = $_request['path'] ? $_request['path'] :'temp';
    $info = array(
      'num'=> $_request['num'],
      'title' => '',    
      'upload' =>'?m=admin&c=upload&a=imageup&savepath='.$path.'&pictitle=banner&dir=images&pc_hash='.$_session['pc_hash'],
      'size' => '4m',
      'type' =>'jpg,png,gif,jpeg',
      'input' => $_request['input'],
      'func' => empty($func) ? 'undefined' : $func,
    );
    include $this->admin_tpl('upload_upload');
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>uploadify</title>
<link rel="stylesheet" type="text/css" href="<?php echo plugin_statics_path?>uploadify/uploadify.css" />
</head>
<body>
<div class="w">
  <div class="bg"></div>
  <div class="wrap" id="wrap">
    <div class="title">
      <h3 class="maintit" id="maintit"><?php echo $info['title'];?></h3>
      <a href="javascript:close();" title="关闭" class="close"></a>
    </div>
    <div class="cont">
      <p class="note">最多上传<strong><?php echo $info['num'];?></strong>个附件,单文件最大<strong><?php echo $info['size'];?></strong>,类型<strong><?php echo $info['type'];?></strong></p>
      <div class="flashwrap">
        <input name="uploadify" id="uploadify" type="file" multiple="true" />
        <!-- <span><input type="checkbox" name="iswatermark" id="iswatermark" /><label>是否添加水印</label></span>-->
      </div>
      <div class="filewarp">
        <fieldset>
          <legend>列表</legend>
          <ul>
          </ul>
          <div id="filequeue">
          </div>
        </fieldset>
      </div>
      <div class="btnbox">
        <button class="btn" id="savebtn">保存</button>
         
        <button class="btn" id="cancelbtn">取消</button>
      </div>
    </div>
    <!--[if ie 6]>
    <iframe frameborder="0" style="width:100%;height:100px;background-color:transparent;position:absolute;top:0;left:0;z-index:-1;"></iframe>
    <![endif]-->
  </div>
</div>
<script src="<?php echo plugin_statics_path?>uploadify/jquery.min.js" type="text/javascript"></script>
<!--防止客户端缓存文件,造成uploadify.js不更新,而引起的“喔唷,崩溃啦”-->
<script>
document.write("<script type='text/javascript' "+ "src='<?php echo plugin_statics_path?>uploadify/jquery.uploadify.js?" + new date()+ "'></s" + "cript>");
</script>     
<script src="<?php echo plugin_statics_path?>uploadify/uploadify-move.js" type="text/javascript"></script>
<script type="text/javascript">
function close(){
  $("iframe.uploadframe", window.parent.document).remove();
}
$("#cancelbtn").click(function(){
  $("iframe.uploadframe", window.parent.document).remove();
  //$('#uploadify').uploadifyclearqueue();
  //$(".filewarp ul li").remove();
});
$(function() {
  $('#uploadify').uploadify({
      'auto'      : true,
      'method'     : 'post',
      'multi'      : true,
      'swf'       : '<?php echo plugin_statics_path?>uploadify/uploadify.swf',
      'uploader'    : '<?php echo $info["upload"];?>',
      'progressdata'  : 'all',
      'queuesizelimit' : '<?php echo $info["num"];?>',
      'uploadlimit'   : 5,
      'filesizelimit'  : '20000kb',
      'filetypedesc'  : 'image files',
      'filetypeexts'  : '*.jpeg; *.jpg; *.png; *.gif',
      'buttonimage'   : '<?php echo plugin_statics_path?>uploadify/select.png',
      'queueid'     : 'filequeue',
      'onuploadstart'  : function(file){
        $('#uploadify').uploadify('settings', 'formdata', {'iswatermark':$("#iswatermark").is(':checked')});       
      },
      'onuploadsuccess' : function(file, data, response){
        $(".filewarp ul").append(setimgcontent(data));
        setuploadfile();
      }
    });
});
function setimgcontent(data){ 
  var obj=eval('('+data+')');
  if(obj.state == 'success'){
    var sli = "";
    sli += '<li class="img">';
    sli += '<img src="' + obj.url + '" width="100" height="100" onerror="this.src=\'<?php echo plugin_statics_path?>uploadify/nopic.png\'">';
    sli += '<input type="hidden" name="fileurl_tmp[]" value="' + obj.url + '">';
    sli += '<a href="javascript:void(0);">删除</a>';
    sli += '</li>';
    return sli;
  }else{
    //window.parent.message(obj.text,8,2);
    alert(obj.msg);
    return;
  }
}
function setuploadfile(){
  $("ul li").each(function(l_i){
    $(this).attr("id", "li_" + l_i);
  })
  $("ul li a").each(function(a_i){
    $(this).attr("rel", "li_" + a_i);
  }).click(function(){
    $.get(
      '?m=admin&c=upload&a=delupload&pc_hash=<?php echo $_session["pc_hash"];?>',{action:"del", filename:$(this).prev().val()},function(){}
    );
    $("#" + this.rel).remove();
  })
}
/*点击保存按钮时
 *判断允许上传数,检测是单一文件上传还是组文件上传
 *如果是单一文件,上传结束后将地址存入$input元素
 *如果是组文件上传,则创建input样式,添加到$input后面
 *隐藏父框架,清空列队,移除已上传文件样式*/
$("#savebtn").click(function(){
  var callback = "<?php echo $info['func'];?>";
  var num = "<?php echo $info['num'];?>";
  var fileurl_tmp = [];
  if(callback != "undefined"){ 
    if(num > 1){ 
       $("input[name^='fileurl_tmp']").each(function(index,dom){
        fileurl_tmp[index] = dom.value;
       }); 
    }else{
      fileurl_tmp = $("input[name^='fileurl_tmp']").val(); 
    }
    eval('window.parent.'+callback+'(fileurl_tmp)');
    $(window.parent.document).find("iframe.uploadframe").remove();
    return;
  }         
  if(num > 1){
      var fileurl_tmp = "";
      $("input[name^='fileurl_tmp']").each(function(){
        fileurl_tmp += '<li rel="'+ this.value +'"><input class="input-text" type="text" name="{$info.input}[]" value="'+ this.value +'" /><a href="javascript:void(0);" onclick="clearpicarr(\''+ this.value +'\',\'\')">删除</a></li>';
      });    
      $(window.parent.document).find("#{$info.input}").append(fileurl_tmp);
  }else{
      $(window.parent.document).find("#{$info.input}").val($("input[name^='fileurl_tmp']").val());
  }
  $(window.parent.document).find("iframe.uploadframe").remove();
});
</script>
</body>
</html>

点评:调用uploadify插件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$(function() {
  $('#uploadify').uploadify({
      'auto'      : true,
      'method'     : 'post',
      'multi'      : true,
      'swf'       : '<?php echo plugin_statics_path?>uploadify/uploadify.swf',
      'uploader'    : '<?php echo $info["upload"];?>',
      'progressdata'  : 'all',
      'queuesizelimit' : '<?php echo $info["num"];?>',
      'uploadlimit'   : 5,
      'filesizelimit'  : '20000kb',
      'filetypedesc'  : 'image files',
      'filetypeexts'  : '*.jpeg; *.jpg; *.png; *.gif',
      'buttonimage'   : '<?php echo plugin_statics_path?>uploadify/select.png',
      'queueid'     : 'filequeue',
      'onuploadstart'  : function(file){
        $('#uploadify').uploadify('settings', 'formdata', {'iswatermark':$("#iswatermark").is(':checked')});       
      },
      'onuploadsuccess' : function(file, data, response){
        $(".filewarp ul").append(setimgcontent(data));
        setuploadfile();
      }
    });
});

点评:表单提交图片文件到服务器,成功后调用回调函数。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* @function imageup
*/
public function imageup()
    // 有文件传入,现在要做的就是把它保存起来
    // 处理上传并返回数据
    // 上传图片框中的描述表单名称,
    $title = htmlspecialchars($_request['pictitle'], ent_quotes);
    // $path = htmlspecialchars($_request['dir'], ent_quotes);
    $savepath = htmlspecialchars($_request['savepath'], ent_quotes);
    $up = new think_upload();
    $path = './uploadfile/'.$savepath;
    //设置属性(上传的位置, 大小, 类型, 名是是否要随机生成)
    $up -> set("path", $path);
    $up -> set("maxsize", 2000000);
    $up -> set("allowtype", array("gif", "png", "jpg","jpeg"));
    $up -> set("israndname", true);
    //使用对象中的upload方法, 就可以上传文件, 方法需要传一个上传表单的名子 pic, 如果成功返回true, 失败返回false
    if($up -> upload("filedata")) {
      $name = $up->getfilename();
      $return_data['url'] = $path.'/'.$name;
      $return_data['title'] = $title;
      $return_data['state'] = 'success';
      exit(json_encode($return_data));
    } else {
      $return_data['state'] = 'failure';
      $return_data['msg']  = $up->geterrormsg();
      exit(json_encode($return_data));
    }
}

点评:后台处理图片上传表单请求,返回图片路径

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
<?php
 /**
  * file: fileupload.class.php 文件上传类fileupload
  * 本类的实例对象用于处理上传文件,可以上传一个文件,也可同时处理多个文件上传
  */
 class think_upload {
  private $path = "./uploadfile";     //上传文件保存的路径
  private $allowtype = array('jpg','gif','png'); //设置限制上传文件的类型
  private $maxsize = 1000000;      //限制文件上传大小(字节)
  private $israndname = true;      //设置是否随机重命名文件, false不随机
  private $originname;       //源文件名
  private $tmpfilename;       //临时文件名
  private $filetype;        //文件类型(文件后缀)
  private $filesize;        //文件大小
  private $newfilename;       //新文件名
  private $errornum = 0;       //错误号
  private $errormess="";       //错误报告消息
  /**
   * 用于设置成员属性($path, $allowtype,$maxsize, $israndname)
   * 可以通过连贯操作一次设置多个属性值
   *@param string $key 成员属性名(不区分大小写)
   *@param mixed $val 为成员属性设置的值
   *@return object   返回自己对象$this,可以用于连贯操作
   */
  function set($key, $val){
   $key = strtolower($key);
   if( array_key_exists( $key, get_class_vars(get_class($this) ) ) ){
    $this->setoption($key, $val);
   }
   return $this;
  }
  /**
   * 调用该方法上传文件
   * @param string $filefile 上传文件的表单名称
   * @return bool    如果上传成功返回数true
   */
  function upload($filefield) {
   $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'];
   /* 如果是多个文件上传则$file["name"]会是一个数组 */
   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();
      /* 上传文件 返回0为成功, 小于0都为错误 */
      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;
   }
  }
  /**
   * 获取上传后的文件名称
   * @param void  没有参数
   * @return string 上传后,新文件的名称, 如果是多文件上传返回数组
   */
  public function getfilename(){
   return $this->newfilename;
  }
  /**
   * 上传失败后,调用该方法则返回,上传出错信息
   * @param void  没有参数
   * @return string 返回上传文件出错的信息报告,如果是多文件上传返回数组
   */
  public function geterrormsg(){
   return $this->errormess;
  }
  /* 设置上传出错信息 */
  private function geterror() {
   $str = "上传文件<font color='red'>{$this->originname}</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.'<br>';
  }
  /* 设置和$_files有关的内容 */
  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;
   }
  }
}

点评:php文件上传类。

然后处理好,图片数据删除对应的文件上传,减轻服务器空间压力。

?
1
2
3
4
5
6
7
8
9
10
11
12
public function delete() {
    $id = intval($_get['id']);
    $this->db->delete(array('id'=>$id));
    // 遍历删除原图片
    $product_img = $this->product_img_db->select(array('product_id'=>$id));
    foreach ($product_img as $k => $v) {
      unlink($v['img']);
    }
    // 删除表数据
    $this->product_img_db->delete(array('product_id'=>$id));
    exit("1");
}

希望本文所述对大家php程序设计有所帮助。

延伸 · 阅读

精彩推荐