jQuery+php+ajax实现无刷新上传文件功能
程序员文章站
2022-03-20 20:25:59
jQuery+php+ajax实现无刷新上传文件功能,还带有上传进度条动画效果,支持图片、视频等大文件上传。 ......
jquery+php+ajax实现无刷新上传文件功能,还带有上传进度条动画效果,支持图片、视频等大文件上传。
js代码
1 <script type='text/javascript' src='js/jquery-2.0.3.min.js'></script> 2 <script type='text/javascript' src='js/jquery.form.js'></script> 3 <script type="text/javascript"> 4 function filesize(ele) { 5 var filesize = (ele.files[0].size / 1024/1024).tofixed(2); 6 $('#big').html(filesize+"mb"); 7 $('#text').html(ele.files[0].name); 8 } 9 $(document).ready(function(e) { 10 var progress = $(".progress"); 11 var progress_bar = $(".progress-bar"); 12 var percent = $('.percent'); 13 $("#del").click(function(){ 14 var objfile=document.getelementsbytagname('input')[2]; 15 objfile.value=""; 16 $("#list").hide(); 17 }); 18 $("#uploadphoto").change(function(){ 19 $("#list").show(); 20 }); 21 $("#ups").click(function(){ 22 var file = $("#uploadphoto").val(); 23 if(file!=""){ 24 $('#uped').html("上传中……"); 25 $("#myupload").ajaxsubmit({ 26 datatype: 'json', //数据格式为json 27 beforesend: function() { //开始上传 28 var percentval = '0%'; 29 progress_bar.width(percentval); 30 percent.html(percentval); 31 }, 32 uploadprogress: function(event, position, total, percentcomplete) { 33 var percentval = percentcomplete + '%'; //获得进度 34 progress_bar.width(percentval); //上传进度条宽度变宽 35 percent.html(percentval); //显示上传进度百分比 36 }, 37 success: function(data) { 38 if(data.status == 1){ 39 var src = data.url; 40 $('#uped').html("上传成功"); 41 //var attstr= '<img src="'+src+'">'; 42 //$(".imglist").append(attstr); 43 //$(".res").html("上传图片"+data.name+"成功,图片大小:"+data.size+"k,文件地址:"+data.url); 44 }else{ 45 $(".res").html(data.content); 46 } 47 }, 48 error:function(xhr){ //上传失败 49 alert("上传失败"); 50 } 51 }); 52 } 53 else{ 54 alert("请选择视频文件"); 55 } 56 }); 57 58 }); 59 </script>
upload.php源代码
1 <?php 2 3 $picname = $_files['uploadfile']['name']; 4 $picsize = $_files['uploadfile']['size']; 5 if ($picname != "") { 6 if ($picsize > 201400000) { //限制上传大小 7 echo '{"status":0,"content":"图片大小不能超过2m"}'; 8 exit; 9 } 10 $type = strstr($picname, '.'); //限制上传格式 11 if ($type != ".gif" && $type != ".jpg" && $type != "png" && $type != ".mp4"&& $type != ".rar") { 12 echo '{"status":2,"content":"文件格式不对!"}'; 13 exit; 14 } 15 $rand = rand(100, 999); 16 $pics = uniqid() . $type; //命名图片名称 17 //上传路径 18 $pic_path = "images/". $pics; 19 move_uploaded_file($_files['uploadfile']['tmp_name'], $pic_path); 20 $myfile = fopen("1/".date("his")."testfile.txt", "w"); 21 } 22 $size = round($picsize/1024,2); //转换成kb 23 echo '{"status":1,"name":"'.$picname.'","url":"'.$pic_path.'","size":"'.$size.'","content":"上传成功"}'; 24 ?>
本文转自,转载请注明出处!