本实例演示了将form表单中选择的文件通过Ajax提交到后台PHP脚本执行上传操作,将PHP将上传后的信息返回,前端JS脚本将反馈信息动态显示在HTML页面中。
前端代码:
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片上传</title> </head> <body> <form id="picupload" enctype="multipart/form-data"> <fieldset> <legend>图片上传测试</legend> <label for='file'></label><input type="file" name="file" id='file'> <p><button type='submit' name='submit' id='submit'>上传</button></p> </fieldset> </form> </body> </html> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script> <script type="text/javascript"> $('#submit').click(function(){ var pic = new FormData(); pic.append("file", $("#file").get(0).files[0]); $.ajax({ url:'upload.php', type:"post", processData: false, contentType: false, data:pic, dataType:'json', success:function(res){ $('span').remove() switch(res.status){ case 0: $('p').after('<span>').next().html(res.msg).css('color','red') break case 1: $('p').after('<span>').next().html(res.msg).css('color','green') break } } }) return false }) </script>
运行实例 »
点击 "运行实例" 按钮查看在线实例
PHP代码:
实例
<?php $randname =date('Hms'); $randname .= rand(0,999)*rand(0,999).'.jpg'; $allow = ['image/jpg','image/jpeg','image/png']; if ($_SERVER['REQUEST_METHOD']=='POST') { $msg = ''; $status = 0; if (isset($_FILES['file'])) { $name = $_FILES['file']['name']; $type = $_FILES['file']['type']; $size = $_FILES['file']['size']; $tmp_name = $_FILES['file']['tmp_name']; $error = $_FILES['file']['error']; if(in_array($type,$allow)){ if ($size < (1024*50)) { move_uploaded_file($tmp_name,'upload/'.$randname); $status = 1; $msg = "图片上传成功"; }else{ $msg = "文件尺寸不得大于50KB!"; } }else{ $msg = "不支持此类型文件上传!"; } }else{ $msg = "文件没有选择!"; } exit(json_encode(['status'=>$status,'msg'=>$msg])); }
运行实例 »
点击 "运行实例" 按钮查看在线实例