php+Ajax 实现无刷新上传文件,上传文件类型时需要使用FormData类,
formData=new FormData(),file_data=$('#upload').prop['files'][0]
formData.append('upload',file_data),php对上传文件进行相应的处理
file.html
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>file</title> <style type="text/css"> form fieldset { width: 30%; background-color: wheat; } </style> </head> <body> <form method="POST" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="100000000"> <fieldset> <legend>上传文件</legend> <p> 上传文件:<input type="file" name="upload" id="upload"> </p> <p align="center"> <button type="submit" name="submit" id="submit">上传</button> </p> </fieldset> </form> <script type="text/javascript" src="js/jquery-3.3.1.js"></script> <script type="text/javascript"> $('#submit').click(function(){ var file_data=$('#upload').prop('files')[0] var formData=new FormData() formData.append('upload',file_data) // alert(formData) $.ajax({ url:'file.php', type:'POST', data:formData, processData:false, contentType:false, dataType:'json', cache:false, success:function(data){ if(data.status== 0){ $('p').find('span').remove(); $('#submit').after('<span>').next().text(data.msg).css('color','green'); } else { $('p').find('span').remove(); $('#submit').after('<span>').next().text(data.msg).css('color','red'); } } }) return false }) </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
file.php
实例
<?php // 检测请求 if ($_SERVER['REQUEST_METHOD'] == 'POST') { // 检测是否上传 if (isset($_FILES['upload'])){ $allow=['image/jpg','image/jpeg','image/png']; if (in_array($_FILES['upload']['type'],$allow)) { if (is_uploaded_file($_FILES['upload']['tmp_name'])){ if (move_uploaded_file($_FILES['upload']['tmp_name'],"upload/{$_FILES['upload']['name']}")) { exit(json_encode(['status'=>0,'msg'=>'上传成功!'])); } } } else { exit(json_encode(['status'=>1,'msg'=>'选择文件类型错误'])); } } // 上传中的错误码 if ($_FILES['upload']['error']>0) { switch ($_FILES['upload']['error']) { case 1: exit(json_encode(['status'=>2,'msg'=>'文件超过了php.ini配置大小'])); break; case 2: exit(json_encode(['status'=>3,'msg'=>'文件超过了html表单配置大小'])); break; case 3: exit(json_encode(['status'=>4,'msg'=>'仅有部分文件上传'])); break; case 4: exit(json_encode(['status'=>5,'msg'=>'没有文件上传'])); break; case 6: exit(json_encode(['status'=>6,'msg'=>'没有可用的临时文件'])); break; case 7: exit(json_encode(['status'=>7,'msg'=>'磁盘已满'])); break; case 9: exit(json_encode(['status'=>8,'msg'=>'上传被终止!'])); break; default: exit(json_encode(['status'=>9,'msg'=>'未知错误'])); break; } // 删除临时文件 if (file_exists($_FILES['upload']['tmp_name']) && is_file($_FILES['upload']['tmp_name'])){ unlink($_FILES['upload']['tmp_name']); } } } else { exit(json_encode(['status'=>10,'msg'=>'不是POST上传'])); }
运行实例 »
点击 "运行实例" 按钮查看在线实例