当前位置:Gxlcms > PHP教程 > PHP实现多图上传结合uploadify插件思路分析

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

时间:2021-07-01 10:21:17 帮助过:22人阅读

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

具体如下:

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

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

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

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

点评:生成一个iframe框。

  1. public function upload(){
  2. $func = $_REQUEST['func'];
  3. $path = $_REQUEST['path'] ? $_REQUEST['path'] :'temp';
  4. $info = array(
  5. 'num'=> $_REQUEST['num'],
  6. 'title' => '',
  7. 'upload' =>'?m=admin&c=upload&a=imageUp&savepath='.$path.'&pictitle=banner&dir=images&pc_hash='.$_SESSION['pc_hash'],
  8. 'size' => '4M',
  9. 'type' =>'jpg,png,gif,jpeg',
  10. 'input' => $_REQUEST['input'],
  11. 'func' => empty($func) ? 'undefined' : $func,
  12. );
  13. include $this->admin_tpl('upload_upload');
  14. }

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5. <title>Uploadify</title>
  6. <link rel="stylesheet" type="text/css" href="<?php echo PLUGIN_STATICS_PATH?>uploadify/uploadify.css" />
  7. </head>
  8. <body>
  9. <p class="W">
  10. <p class="Bg"></p>
  11. <p class="Wrap" id="Wrap">
  12. <p class="Title">
  13. <h3 class="MainTit" id="MainTit"><?php echo $info['title'];?></h3>
  14. <a href="javascript:Close();" title="关闭" class="Close"></a>
  15. </p>
  16. <p class="Cont">
  17. <p class="Note">最多上传<strong><?php echo $info['num'];?></strong>个附件,单文件最大<strong><?php echo $info['size'];?></strong>,类型<strong><?php echo $info['type'];?></strong></p>
  18. <p class="flashWrap">
  19. <input name="uploadify" id="uploadify" type="file" multiple="true" />
  20. <!-- <span><input type="checkbox" name="iswatermark" id="iswatermark" /><label>是否添加水印</label></span>-->
  21. </p>
  22. <p class="fileWarp">
  23. <fieldset>
  24. <legend>列表</legend>
  25. <ul>
  26. </ul>
  27. <p id="fileQueue">
  28. </p>
  29. </fieldset>
  30. </p>
  31. <p class="btnBox">
  32. <button class="btn" id="SaveBtn">保存</button>
  33. <button class="btn" id="CancelBtn">取消</button>
  34. </p>
  35. </p>
  36. <!--[if IE 6]>
  37. <iframe frameborder="0" style="width:100%;height:100px;background-color:transparent;position:absolute;top:0;left:0;z-index:-1;"></iframe>
  38. <![endif]-->
  39. </p>
  40. </p>
  41. <script src="<?php echo PLUGIN_STATICS_PATH?>uploadify/jquery.min.js" type="text/javascript"></script>
  42. <!--防止客户端缓存文件,造成uploadify.js不更新,而引起的“喔唷,崩溃啦”-->
  43. <script>
  44. document.write("<script type='text/javascript' "+ "src='<?php echo PLUGIN_STATICS_PATH?>uploadify/jquery.uploadify.js?" + new Date()+ "'></s" + "cript>");
  45. </script>
  46. <script src="<?php echo PLUGIN_STATICS_PATH?>uploadify/uploadify-move.js" type="text/javascript"></script>
  47. <script type="text/javascript">
  48. function Close(){
  49. $("iframe.uploadframe", window.parent.document).remove();
  50. }
  51. $("#CancelBtn").click(function(){
  52. $("iframe.uploadframe", window.parent.document).remove();
  53. //$('#uploadify').uploadifyClearQueue();
  54. //$(".fileWarp ul li").remove();
  55. });
  56. $(function() {
  57. $('#uploadify').uploadify({
  58. 'auto' : true,
  59. 'method' : 'post',
  60. 'multi' : true,
  61. 'swf' : '<?php echo PLUGIN_STATICS_PATH?>uploadify/uploadify.swf',
  62. 'uploader' : '<?php echo $info["upload"];?>',
  63. 'progressData' : 'all',
  64. 'queueSizeLimit' : '<?php echo $info["num"];?>',
  65. 'uploadLimit' : 5,
  66. 'fileSizeLimit' : '20000KB',
  67. 'fileTypeDesc' : 'Image Files',
  68. 'fileTypeExts' : '*.jpeg; *.jpg; *.png; *.gif',
  69. 'buttonImage' : '<?php echo PLUGIN_STATICS_PATH?>uploadify/select.png',
  70. 'queueID' : 'fileQueue',
  71. 'onUploadStart' : function(file){
  72. $('#uploadify').uploadify('settings', 'formData', {'iswatermark':$("#iswatermark").is(':checked')});
  73. },
  74. 'onUploadSuccess' : function(file, data, response){
  75. $(".fileWarp ul").append(SetImgContent(data));
  76. SetUploadFile();
  77. }
  78. });
  79. });
  80. function SetImgContent(data){
  81. var obj=eval('('+data+')');
  82. if(obj.state == 'SUCCESS'){
  83. var sLi = "";
  84. sLi += '<li class="img">';
  85. sLi += '<img src="' + obj.url + '" width="100" height="100" onerror="this.src=\'<?php echo PLUGIN_STATICS_PATH?>uploadify/nopic.png\'">';
  86. sLi += '<input type="hidden" name="fileurl_tmp[]" value="' + obj.url + '">';
  87. sLi += '<a href="javascript:void(0);">删除</a>';
  88. sLi += '</li>';
  89. return sLi;
  90. }else{
  91. //window.parent.message(obj.text,8,2);
  92. alert(obj.msg);
  93. return;
  94. }
  95. }
  96. function SetUploadFile(){
  97. $("ul li").each(function(l_i){
  98. $(this).attr("id", "li_" + l_i);
  99. })
  100. $("ul li a").each(function(a_i){
  101. $(this).attr("rel", "li_" + a_i);
  102. }).click(function(){
  103. $.get(
  104. '?m=admin&c=upload&a=delupload&pc_hash=<?php echo $_SESSION["pc_hash"];?>',{action:"del", filename:$(this).prev().val()},function(){}
  105. );
  106. $("#" + this.rel).remove();
  107. })
  108. }
  109. /*点击保存按钮时
  110. *判断允许上传数,检测是单一文件上传还是组文件上传
  111. *如果是单一文件,上传结束后将地址存入$input元素
  112. *如果是组文件上传,则创建input样式,添加到$input后面
  113. *隐藏父框架,清空列队,移除已上传文件样式*/
  114. $("#SaveBtn").click(function(){
  115. var callback = "<?php echo $info['func'];?>";
  116. var num = "<?php echo $info['num'];?>";
  117. var fileurl_tmp = [];
  118. if(callback != "undefined"){
  119. if(num > 1){
  120. $("input[name^='fileurl_tmp']").each(function(index,dom){
  121. fileurl_tmp[index] = dom.value;
  122. });
  123. }else{
  124. fileurl_tmp = $("input[name^='fileurl_tmp']").val();
  125. }
  126. eval('window.parent.'+callback+'(fileurl_tmp)');
  127. $(window.parent.document).find("iframe.uploadframe").remove();
  128. return;
  129. }
  130. if(num > 1){
  131. var fileurl_tmp = "";
  132. $("input[name^='fileurl_tmp']").each(function(){
  133. 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>';
  134. });
  135. $(window.parent.document).find("#{$info.input}").append(fileurl_tmp);
  136. }else{
  137. $(window.parent.document).find("#{$info.input}").val($("input[name^='fileurl_tmp']").val());
  138. }
  139. $(window.parent.document).find("iframe.uploadframe").remove();
  140. });
  141. </script>
  142. </body>
  143. </html>

点评:调用uploadify插件

  1. $(function() {
  2. $('#uploadify').uploadify({
  3. 'auto' : true,
  4. 'method' : 'post',
  5. 'multi' : true,
  6. 'swf' : '<?php echo PLUGIN_STATICS_PATH?>uploadify/uploadify.swf',
  7. 'uploader' : '<?php echo $info["upload"];?>',
  8. 'progressData' : 'all',
  9. 'queueSizeLimit' : '<?php echo $info["num"];?>',
  10. 'uploadLimit' : 5,
  11. 'fileSizeLimit' : '20000KB',
  12. 'fileTypeDesc' : 'Image Files',
  13. 'fileTypeExts' : '*.jpeg; *.jpg; *.png; *.gif',
  14. 'buttonImage' : '<?php echo PLUGIN_STATICS_PATH?>uploadify/select.png',
  15. 'queueID' : 'fileQueue',
  16. 'onUploadStart' : function(file){
  17. $('#uploadify').uploadify('settings', 'formData', {'iswatermark':$("#iswatermark").is(':checked')});
  18. },
  19. 'onUploadSuccess' : function(file, data, response){
  20. $(".fileWarp ul").append(SetImgContent(data));
  21. SetUploadFile();
  22. }
  23. });
  24. });

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

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

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

  1. <?php
  2. /**
  3. * file: fileupload.class.php 文件上传类FileUpload
  4. * 本类的实例对象用于处理上传文件,可以上传一个文件,也可同时处理多个文件上传
  5. */
  6. class think_upload {
  7. private $path = "./uploadfile"; //上传文件保存的路径
  8. private $allowtype = array('jpg','gif','png'); //设置限制上传文件的类型
  9. private $maxsize = 1000000; //限制文件上传大小(字节)
  10. private $israndname = true; //设置是否随机重命名文件, false不随机
  11. private $originName; //源文件名
  12. private $tmpFileName; //临时文件名
  13. private $fileType; //文件类型(文件后缀)
  14. private $fileSize; //文件大小
  15. private $newFileName; //新文件名
  16. private $errorNum = 0; //错误号
  17. private $errorMess=""; //错误报告消息
  18. /**
  19. * 用于设置成员属性($path, $allowtype,$maxsize, $israndname)
  20. * 可以通过连贯操作一次设置多个属性值
  21. *@param string $key 成员属性名(不区分大小写)
  22. *@param mixed $val 为成员属性设置的值
  23. *@return object 返回自己对象$this,可以用于连贯操作
  24. */
  25. function set($key, $val){
  26. $key = strtolower($key);
  27. if( array_key_exists( $key, get_class_vars(get_class($this) ) ) ){
  28. $this->setOption($key, $val);
  29. }
  30. return $this;
  31. }
  32. /**
  33. * 调用该方法上传文件
  34. * @param string $fileFile 上传文件的表单名称
  35. * @return bool 如果上传成功返回数true
  36. */
  37. function upload($fileField) {
  38. $return = true;
  39. /* 检查文件路径是滞合法 */
  40. if( !$this->checkFilePath() ) {
  41. $this->errorMess = $this->getError();
  42. return false;
  43. }
  44. /* 将文件上传的信息取出赋给变量 */
  45. $name = $_FILES[$fileField]['name'];
  46. $tmp_name = $_FILES[$fileField]['tmp_name'];
  47. $size = $_FILES[$fileField]['size'];
  48. $error = $_FILES[$fileField]['error'];
  49. /* 如果是多个文件上传则$file["name"]会是一个数组 */
  50. if(is_Array($name)){
  51. $errors=array();
  52. /*多个文件上传则循环处理 , 这个循环只有检查上传文件的作用,并没有真正上传 */
  53. for($i = 0; $i < count($name); $i++){
  54. /*设置文件信息 */
  55. if($this->setFiles($name[$i],$tmp_name[$i],$size[$i],$error[$i] )) {
  56. if(!$this->checkFileSize() || !$this->checkFileType()){
  57. $errors[] = $this->getError();
  58. $return=false;
  59. }
  60. }else{
  61. $errors[] = $this->getError();
  62. $return=false;
  63. }
  64. /* 如果有问题,则重新初使化属性 */
  65. if(!$return)
  66. $this->setFiles();
  67. }
  68. if($return){
  69. /* 存放所有上传后文件名的变量数组 */
  70. $fileNames = array();
  71. /* 如果上传的多个文件都是合法的,则通过销魂循环向服务器上传文件 */
  72. for($i = 0; $i < count($name); $i++){
  73. if($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i] )) {
  74. $this->setNewFileName();
  75. if(!$this->copyFile()){
  76. $errors[] = $this->getError();
  77. $return = false;
  78. }
  79. $fileNames[] = $this->newFileName;
  80. }
  81. }
  82. $this->newFileName = $fileNames;
  83. }
  84. $this->errorMess = $errors;
  85. return $return;
  86. /*上传单个文件处理方法*/
  87. } else {
  88. /* 设置文件信息 */
  89. if($this->setFiles($name,$tmp_name,$size,$error)) {
  90. /* 上传之前先检查一下大小和类型 */
  91. if($this->checkFileSize() && $this->checkFileType()){
  92. /* 为上传文件设置新文件名 */
  93. $this->setNewFileName();
  94. /* 上传文件 返回0为成功, 小于0都为错误 */
  95. if($this->copyFile()){
  96. return true;
  97. }else{
  98. $return=false;
  99. }
  100. }else{
  101. $return=false;
  102. }
  103. } else {
  104. $return=false;
  105. }
  106. //如果$return为false, 则出错,将错误信息保存在属性errorMess中
  107. if(!$return)
  108. $this->errorMess=$this->getError();
  109. return $return;
  110. }
  111. }
  112. /**
  113. * 获取上传后的文件名称
  114. * @param void 没有参数
  115. * @return string 上传后,新文件的名称, 如果是多文件上传返回数组
  116. */
  117. public function getFileName(){
  118. return $this->newFileName;
  119. }
  120. /**
  121. * 上传失败后,调用该方法则返回,上传出错信息
  122. * @param void 没有参数
  123. * @return string 返回上传文件出错的信息报告,如果是多文件上传返回数组
  124. */
  125. public function getErrorMsg(){
  126. return $this->errorMess;
  127. }
  128. /* 设置上传出错信息 */
  129. private function getError() {
  130. $str = "上传文件<font color='red'>{$this->originName}</font>时出错 : ";
  131. switch ($this->errorNum) {
  132. case 4: $str .= "没有文件被上传"; break;
  133. case 3: $str .= "文件只有部分被上传"; break;
  134. case 2: $str .= "上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值"; break;
  135. case 1: $str .= "上传的文件超过了php.ini中upload_max_filesize选项限制的值"; break;
  136. case -1: $str .= "未允许类型"; break;
  137. case -2: $str .= "文件过大,上传的文件不能超过{$this->maxsize}个字节"; break;
  138. case -3: $str .= "上传失败"; break;
  139. case -4: $str .= "建立存放上传文件目录失败,请重新指定上传目录"; break;
  140. case -5: $str .= "必须指定上传文件的路径"; break;
  141. default: $str .= "未知错误";
  142. }
  143. return $str.'<br>';
  144. }
  145. /* 设置和$_FILES有关的内容 */
  146. private function setFiles($name="", $tmp_name="", $size=0, $error=0) {
  147. $this->setOption('errorNum', $error);
  148. if($error)
  149. return false;
  150. $this->setOption('originName', $name);
  151. $this->setOption('tmpFileName',$tmp_name);
  152. $aryStr = explode(".", $name);
  153. $this->setOption('fileType', strtolower($aryStr[count($aryStr)-1]));
  154. $this->setOption('fileSize', $size);
  155. return true;
  156. }
  157. /* 为单个成员属性设置值 */
  158. private function setOption($key, $val) {
  159. $this->$key = $val;
  160. }
  161. /* 设置上传后的文件名称 */
  162. private function setNewFileName() {
  163. if ($this->israndname) {
  164. $this->setOption('newFileName', $this->proRandName());
  165. } else{
  166. $this->setOption('newFileName', $this->originName);
  167. }
  168. }
  169. /* 检查上传的文件是否是合法的类型 */
  170. private function checkFileType() {
  171. if (in_array(strtolower($this->fileType), $this->allowtype)) {
  172. return true;
  173. }else {
  174. $this->setOption('errorNum', -1);
  175. return false;
  176. }
  177. }
  178. /* 检查上传的文件是否是允许的大小 */
  179. private function checkFileSize() {
  180. if ($this->fileSize > $this->maxsize) {
  181. $this->setOption('errorNum', -2);
  182. return false;
  183. }else{
  184. return true;
  185. }
  186. }
  187. /* 检查是否有存放上传文件的目录 */
  188. private function checkFilePath() {
  189. if(empty($this->path)){
  190. $this->setOption('errorNum', -5);
  191. return false;
  192. }
  193. if (!file_exists($this->path) || !is_writable($this->path)) {
  194. if (!@mkdir($this->path, 0755)) {
  195. $this->setOption('errorNum', -4);
  196. return false;
  197. }
  198. }
  199. return true;
  200. }
  201. /* 设置随机文件名 */
  202. private function proRandName() {
  203. $fileName = date('YmdHis')."_".rand(100,999);
  204. return $fileName.'.'.$this->fileType;
  205. }
  206. /* 复制上传文件到指定的位置 */
  207. private function copyFile() {
  208. if(!$this->errorNum) {
  209. $path = rtrim($this->path, '/').'/';
  210. $path .= $this->newFileName;
  211. if (@move_uploaded_file($this->tmpFileName, $path)) {
  212. return true;
  213. }else{
  214. $this->setOption('errorNum', -3);
  215. return false;
  216. }
  217. } else {
  218. return false;
  219. }
  220. }
  221. }

点评:php文件上传类。

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

php使用PDO下exec()函数实现查询执行后受影响行数的方法

php json相关函数的用法详解

php mysql_list_dbs()函数的用法详解

以上就是PHP实现多图上传结合uploadify插件思路分析的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行