本文实例讲述了php+iframe 实现上传文件功能。分享给大家供大家参考,具体如下:
我们通过动态的创建iframe,修改form的target,来实现无跳转的文件上传。
具体的实现步骤
1.捕捉表单提交事件
2.创建一个iframe
3.修改表单的target,指向iframe
4.删除iframe
file.html代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<!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代码如下:
1
2
3
4
5
6
7
8
9
10
11
|
<?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程序设计有所帮助。
原文链接:https://www.cnblogs.com/jkko123/p/6294583.html