本文实例讲述了php+iframe 实现上传文件功能。分享给大家供大家参考,具体如下:
我们通过动态的创建iframe,修改form的target,来实现无跳转的文件上传。
具体的实现步骤
1.捕捉表单提交事件
2.创建一个iframe
3.修改表单的target,指向iframe
4.删除iframe
file.html代码如下:
<!DOCTYPE HTML> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form action="upfile.php" method="post" id="upfileForm" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" name="submit" value="上传" /> </form> <div id="result"></div> </body> <script type="text/javascript" src="./jquery.js"></script> <script type="text/javascript"> $("#upfileForm").bind("submit", function() { var ifrName = 'upfile' + Math.random(); var ifr = $("<iframe name='" + ifrName + "' width='0' height='0' frameborder='0'></iframe>"); $("body").append(ifr); $(this).attr("target", ifrName); }); </script> </html>
upfile.php代码如下:
<?php $uploadDir = './upload/'; if(!file_exists($uploadDir)) { @mkdir($uploadDir, 0777, true); } $uploadFile = $uploadDir . basename($_FILES['file']['name']); if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) { echo "<script>parent.document.getElementById('result').innerHTML='OK';</script>"; } else { echo "<script>parent.document.getElementById('result').innerHTML='NO';</script>"; }
更多关于PHP相关内容感兴趣的读者可查看本站专题