代码通过move_uploaded_file()函数实现文件上传功能,以及$_FILES的属性来判断文件的状态,再返回json数据显示在button下面,效果图如下:
代码如下:
前端:
实例
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> body{ font-family: microsoft yahei; } .box{ margin: 30px auto; width: 450px; background-color: #DCDCDC; height: 140px; border-radius: 5px; text-align: center; } .box p{ text-align: center; margin-left: 20px; padding-top: 20px; } button{ margin: auto; width: 70px; height: 30px; font-size: 13px; border: none; background-color:#1E90FF; border-radius: 5px; cursor: pointer; color: #fff; } </style> </head> <body> <div class="box"> <p> 上传文件:<input type="file" id="file"> </p> <button id="upload">开始上传</button> </div> </body> </html> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('button').click(function () { if($('#file').val().length==0){ $('#file').parent($('span').remove()) $('#upload').after('<span style="padding-left:10px; color: #ff0000;font-size: 14px;">没有选择文件!</span>') }else{ var files=$("#file")[0].files[0] var formdata = new FormData() formdata.append('files',files) $.ajax({ url:'upload.php', type:'POST', data:formdata, dataType:'JSON', processData:false, contentType:false, success:function (status) { $('#upload').parent($('span').remove()) $('#upload').after('<br><span style="position:relative;top:10px; color:#008800;font-size: 14px;">'+status.msg+'</span>') } }) } }) }) </script>
运行实例 »
点击 "运行实例" 按钮查看在线实例
后台:
实例
<?php ini_set('date.timezone','Asia/Shanghai'); if($_SERVER['REQUEST_METHOD']=="POST"){ if(isset($_FILES['files'])){ $img_type=['image/jpg','image/jpeg','image/png']; if(in_array($_FILES['files']['type'], $img_type)){ $_FILES["files"]["name"] = date('YmdHis').$_FILES["files"]["name"]; if(move_uploaded_file($_FILES["files"]["tmp_name"],"upload/". $_FILES["files"]["name"])){ echo json_encode(['msg'=>'上传成功!文件名是:'. $_FILES["files"]["name"]]); } else { echo json_encode(['msg'=>'上传失败']); } }else{ echo json_encode(['msg'=>'格式有误!']); } }else{ echo json_encode(['msg'=>'没有选择文件!']); } if($_FILES['files']['error']>0){ switch ($_FILES['files']['error']) { case 1: echo json_encode(['msg'=>'文件超过php.ini中的默认大小']); break; case 2: echo json_encode(['msg'=>'文件超过表单设置大小']); break; case 3: echo json_encode(['msg'=>'文件只有一部分上传']); break; case 4: echo json_encode(['msg'=>'没有文件上传']); break; case 6: echo json_encode(['msg'=>'没有临时文件夹']); break; case 8: echo json_encode(['msg'=>'上传意外终止']); break; default: echo json_encode(['msg'=>'未知错误']); break; } } }
运行实例 »
点击 "运行实例" 按钮查看在线实例