php批量上传图片并预览
2015-01-18 20:44
309 查看
<?php /** 思路: 注意 jquery.ocupload-1.1.2.js是别人写的上传的js,我也是抄的............... 我看不懂。 不过原理很简单,这也是用的form表单提交,单击按钮时动态的添加了一个from表单跟input,然后改写了一下ajax,提交数据。 1、input多选:html5的input多加了属性multiple。 2、多文件同时上传就是一个数组,用for循环就搞定了。 3、显示图片也是动态添加一个img元素,在用AJAX返回的图片地址就行了。 存数据库:图片的信息已存到显示图片的下一个input的value中(见bindRelate()函数),点提交就可以从value中取出数据,跟其他数据一起存数据库。 **/ //ajax预览图片 $img_size = "1000000"; //设置上传文件大小 $img_type = array('image/jpe','image/jpeg','image/png','image/gif'); //设置上传文件类型 $status = "1"; $info = ""; $data = array(); $file = $_FILES['upload_images']; $url = date('Ymd'); //$file['type'] = images/jpg,images/png; if(!file_exists($url)){ @mkdir($url, 0777, true); //创建文件夹并给最高权限 } for($i=0;$i<count($file['name']);$i++){ //for循环上传文件 if(!empty($_FILES['upload_images']['error'][$i])){ //限制信息可以自己搞,我搞的也不完善 $status .= "1"; $info .= '上传文件失败'; } elseif (empty($file['tmp_name'][$i]) || $file['tmp_name'][$i] == 'none'){ $status .= "1"; $info .= '没有选择上传文件'; } elseif ($img_size<$file['size'][$i]){ $status .= "1"; $info .= $file['name'][$i].'文件太大'; } elseif (!in_array($file['type'][$i],$img_type)){ $status .= "1"; $info .= $file['name'][$i].'不合符文件类型'; } else { $str="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLMNBVCXZ"; //设置4位数字的随机数 $s=""; for($j=1;$j<5;$j++){ $k=rand(1,52); $s = $s.substr($str,$k-1,1); } $format = pathinfo($file['name'][$i],PATHINFO_EXTENSION); //取到上传文件的后缀 即gif $img_name = time().$s.'.'.$format; //重构复制文件名字 $data[$i] = date('Ymd').'/'.$img_name; //构造回调参数 move_uploaded_file($file['tmp_name'][$i],$url.'/'.$img_name); //复制文件 } } echo json_encode(array('status'=>$status,'info'=>$info,'data'=>$file['tmp_name'])); //把状态、信息跟数据返回ajax ?>
1、$_FILES的简单介绍:
$_FILES是文件上传的超全局变量:其实文件上传只是将文件临时存放到一个目录,上传完成该目录页会被删除。需要在文件上传完成之前将临时文件复制走。
$_FILES['fileName']['name']-----------------------被上传文件的名称
$_FILES['fileName']['type']-------------------------被上传文件的类型
$_FILES['fileName']['size']--------------------------被上传文件的大小,以字节计。
$_FILES['fileName']['tmp_name']-----------------存储在服务器的文件的临时副本名称(包含了文件的临时存放目录,文件上传完成将被删除)
$_FILES['fileName']['error']-------------------------文件上传导致的错误代码
$_FILES['fileName']['error'] == 0 代表正常
$_FILES['fileName']['error'] == 1 文件大小超出服务器空间大小
$_FILES['fileName']['error'] == 2 要上传的文件大小超出浏览器限制
$_FILES['fileName']['error'] == 3 文件仅部分被传
$_FILES['fileName']['error'] == 4 没有找到要上传的文件
$_FILES['fileName']['error'] == 5 服务器临时文件丢失
$_FILES['fileName']['error'] == 6 文件写入到临时文件夹出错
2、方法:(input的multiple属性是html5才有的)
jquery.ocupload-1.1.2.js:
/* * One Click Upload - jQuery Plugin * Copyright (c) 2008 Michael Mitchell - http://www.michaelmitchell.co.nz */ (function($){ $.fn.upload = function(options) { /** Merge the users options with our defaults */ options = $.extend({ name: 'file', enctype: 'multipart/form-data', action: '', autoSubmit: true, onSubmit: function() {}, onComplete: function() {}, onSelect: function() {}, params: {} }, options); return new $.ocupload(this, options); }, $.ocupload = function(element, options) { /** Fix scope problems */ var self = this; /** A unique id so we can find our elements later */ var id = new Date().getTime().toString().substr(8); /** Upload Iframe */ var iframe = $( '<iframe '+ 'id="iframe'+id+'" '+ 'name="iframe'+id+'"'+ '></iframe>' ).css({ display: 'none' }); /** Form */ var form = $( '<form '+ 'method="post" '+ 'enctype="'+options.enctype+'" '+ 'action="'+options.action+'" '+ 'target="iframe'+id+'"'+ '></form>' ).css({ margin: 0, padding: 0 }); /** File Input */ var input = $( '<input '+ 'name="'+options.name+'" '+ 'type="file" '+ 'multiple="multiple"'+ '/>' ).css({ position: 'relative', display: 'block', marginLeft: -175+'px', opacity: 0 }); /** Put everything together */ element.wrap('<div></div>'); //container form.append(input); element.after(form); element.after(iframe); /** Find the container and make it nice and snug */ var container = element.parent().css({ position: 'relative', height: element.outerHeight()+'px', width: element.outerWidth()+'px', overflow: 'hidden', cursor: 'pointer', margin: 0, padding: 0 }); /** Put our file input in the right place */ input.css('marginTop', -container.height()-10+'px'); /** Move the input with the mouse to make sure it get clicked! */ container.mousemove(function(e){ input.css({ top: e.pageY-container.offset().top+'px', left: e.pageX-container.offset().left+'px' }); }); /** Watch for file selection */ input.change(function() { /** Do something when a file is selected. */ self.onSelect(); /** Submit the form automaticly after selecting the file */ if(self.autoSubmit) { self.submit(); } }); /** Methods */ $.extend(this, { autoSubmit: true, onSubmit: options.onSubmit, onComplete: options.onComplete, onSelect: options.onSelect, /** get filename */ filename: function() { return input.attr('value'); }, /** get/set params */ params: function(params) { var params = params ? params : false; if(params) { options.params = $.extend(options.params, params); } else { return options.params; } }, /** get/set name */ name: function(name) { var name = name ? name : false; if(name) { input.attr('name', value); } else { return input.attr('name'); } }, /** get/set action */ action: function(action) { var action = action ? action : false; if(action) { form.attr('action', action); } else { return form.attr('action'); } }, /** get/set enctype */ enctype: function(enctype 4000 ) { var enctype = enctype ? enctype : false; if(enctype) { form.attr('enctype', enctype); } else { return form.attr('enctype'); } }, /** set options */ set: function(obj, value) { var value = value ? value : false; function option(action, value) { switch(action) { default: throw new Error('[jQuery.ocupload.set] \''+action+'\' is an invalid option.'); break; case 'name': self.name(value); break; case 'action': self.action(value); break; case 'enctype': self.enctype(value); break; case 'params': self.params(value); break; case 'autoSubmit': self.autoSubmit = value; break; case 'onSubmit': self.onSubmit = value; break; case 'onComplete': self.onComplete = value; break; case 'onSelect': self.onSelect = value; break; } } if(value) { option(obj, value); } else { $.each(obj, function(key, value) { option(key, value); }); } }, /** Submit the form */ submit: function() { /** Do something before we upload */ this.onSubmit(); /** add additional paramters before sending */ $.each(options.params, function(key, value) { form.append($( '<input '+ 'type="hidden" '+ 'name="'+key+'" '+ 'value="'+value+'" '+ '/>' )); }); /** Submit the actual form */ form.submit(); /** Do something after we are finished uploading */ iframe.unbind().load(function() { /** Get a response from the server in plain text */ var myFrame = document.getElementById(iframe.attr('name')); var response = $(myFrame.contentWindow.document.body).text(); /** Do something on complete */ self.onComplete(response); //done :D }); } }); } })(jQuery);
base.js:
$(function(){ //上传图片 $('#btn_upload_images').upload({ //upload是ajax的改写, name: 'upload_images[]', //相当于要上传的那个input的name,也就是$_FILES[]要用的。 action: 'upload.php', enctype: 'multipart/form-data', //告诉表单你要提交的是文件。 autoSubmit: true, onSubmit: function() {}, onComplete: function(data) { //相当于AJAX的回调函数 data = $.parseJSON(data); //data就是图片的存储地址 //alert(data); //alert(data.status); //alert(data.info); alert(data.data); //alert(data.data[0]); //alert(data.data.length); if(data.status==1){ if(data.data[0] == '/'){ bindRelate(data.data); } else { for(i=0;i<data.data.length;i++){ bindRelate(data.data[i],i); //上传成功调用显示图片函数。 } } } else { alert(data.info); //上传失败显示错误信息 } } }); //删除影片相关图片 $('.delete_relate_img').live('click', function(){ var _this = $(this); //Ajax提交删除图片 var url = "del.php"; $.ajax({ type: "POST", url: url, data:"imgurl="+$(this).next().val(), dataType:"json", success: function(data){ //alert(data.status); if (data.status == 1) { _this.parent().remove(); } else{ alert(data.info); _this.parent().remove(); } }, error: function(){alert("向服务器发送AJAX请求失败!");} }); }); //显示所有上传的影片相关图片 var bindRelate = function(src,num){ var imgStr="<li><img src='"+src+"' width='' height=''/><a href='#' class='delete_relate_img'>删除</a><input type='hidden' id='img_relate"+num+"' name='img_relate2[]' value='"+src+"'/></li>"; $('#show_relate_img').append(imgStr); }; })
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a target=_blank href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>"> <html xmlns="<a target=_blank href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>文件上传</title> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript" src="jquery.ocupload-1.1.2.js"></script> <script type="text/javascript" src="base.js"></script> </head> <body> <p>添加图片:</p> <p><table><tr> <td><input type='button' value=' 上传相关图片... ' id="btn_upload_images" class="btn_upload_images"/></td> <td><span class="cr"> * 可以重复选择上传多张图片,只支持jpe,jpeg,png,gif类型图片</span></td> </tr></table></p> <p><ul id="show_relate_img" class='ul-movie-img'></ul></p> <input type="button" id="sub" value="提交" /> </body>
</html>
相关文章推荐
- php图片上传存储源码,可实现预览
- flex3.5 批量上传图片+预览
- 纯javascript代码实现浏览器图片选择预览、旋转、批量上传
- C# 结合html5 批量上传文件和图片预览
- HTML5 CSS3 经典案例:无插件拖拽上传图片 (支持预览与批量) (一)
- php图片上传存储源码,可实现预览
- HTML5 CSS3 经典案例:无插件拖拽上传图片 (支持预览与批量) (一)
- php 图片上传并预览效果
- PHP批量上传图片的具体实现方法介绍.
- php图片上传与预览
- php批量上传二[带预览]
- asp.net 图片批量上传预览,在Silverlight页面中读取并滚动显示
- 新的flash批量上传(支持图片预览)
- php+js实现图片的上传、裁剪、预览、提交示例
- php图片上传,可实现预览
- PHP批量上传图片的具体实现方式
- HTML5 CSS3 经典案例:无插件拖拽上传图片 (支持预览与批量) (二)
- php批量上传图片并把图片名放入数据库