在很多项目中都会叫用户上传东西这些的,自从接触了jquery 和ajax之后就不管做什么,首先都会想到这个,我这个人呢?是比较重视客户体验的,这次我这边负责的是后台板块,然后就有一块是要求用户上传照片的,当然就想到了无刷新上传了呀,一般的jquery+ajax的话传递给php的data我习惯用json,然后就不知道怎么怎么把$_FILES数组中的内容给php,我要用move_uploaded_file这个函数来吧$_FILES['file']['tmp_name']移动到我想要的位置,tmp_name是上传的临时路径了啦,具体参看手册,数组中有很多关于文件的记录的。查询了很多记录,要达到无刷新上传,那么有的解决方法是用生成frame来做得,找了很久很久,找到一个插件,jquery的,叫jquery.form,是个表单插件,有兴趣的同学可以上网查看,我这里只说我这个的实现而已,ok,上代码:
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 <title>jQuery+php实现ajax文件上传</title> 6 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> 7 <script type="text/javascript" src="jquery.form.js"></script> 8 <style type="text/css"> 9 .opacity{10 opacity:0.3;11 filter:alpha(opacity=30);12 background-color: black;13 }14 .mask{15 16 position:fixed;17 _position:absolute;18 top:0;19 left:0;20 z-index:1000;21 }22 #main{23 width:980px;24 margin:0px auto;25 text-align:center;26 }27 #loading{28 background-color:white;29 width:100px;30 height:20px;31 position:fixed;32 _position:absolute;33 text-align:center;34 border-style:groove;35 z-index:2000;36 }37 </style>38 </head>39 40 <body>41 <div id="main">42 <div class="demo">43 <div class="btn">44 <span>添加附件</span>45 <input id="fileupload" type="file" name="mypic">46 </div>47 <div id="zhezhao">48 <div id="loading">49 <span class="bar"><img src="loading.gif" /></span><span class="percent">0%</span >50 </div>51 </div>52 <div id="showimg"></div>53 </div>54 </div>55 56 <script type="text/javascript">57 $(function () {58 var percent = $('.percent');59 var showimg = $('#showimg');60 var zhezhao = $("#zhezhao");61 var btn = $(".btn span");62 zhezhao.hide();63 $("#fileupload").wrap("<form id='myupload' action='action.php' method='post' enctype='multipart/form-data'></form>");64 $("#fileupload").change(function(){65 $("#myupload").ajaxSubmit({66 dataType: 'json',67 beforeSend: function() {68 showimg.empty();69 zhezhao.show();70 var percentVal = '0%';71 percent.html(percentVal);72 btn.html("上传中...");73 },74 uploadProgress: function(event, position, total, percentComplete) {75 $("#zhezhao").attr("class","mask opacity");76 $("#zhezhao").css('width',$(window).width());77 $("#zhezhao").css('height',$(window).height());78 var percentVal = percentComplete + '%';79 percent.html(percentVal);80 $("#loading").css('margin-left',$(window).width()/2-50);81 $("#loading").css('margin-top',$(window).height()/2-10);82 },83 success: function(data) {84 var img = "files/"+data.pic;85 zhezhao.hide();86 showimg.html("<img src='"+img+"'>");87 btn.html("添加附件");88 },89 error:function(xhr){90 btn.html("上传失败");91 }92 });93 });94 });95 </script>96 97 </body>98 </html>