黑帽联盟

标题: php利用iframe实现无刷新文件上传功能的代码 [打印本页]

作者: yun    时间: 2017-3-14 22:22
标题: php利用iframe实现无刷新文件上传功能的代码
上传原理很简单就是利用表单的打开方式为iframe的id名,这样就可以在当前页面的iframe打来了,实现文件上传,再利用js返回上传结果,下面直接上代码:
  1. <html>
  2.   <head>
  3.   <title>无刷新上传文件</title>
  4.   <meta Content-type="text/html" charset="utf-8" />
  5.   <script type="text/网页特效">
  6.   function startUpload() {
  7.   document.getElementById('processing').innerHTML = 'loding...';
  8.   return true;
  9.   }
  10.   function stopUpload(rel){
  11.   var msg;
  12.   switch (rel) {
  13.   case 0:
  14.   msg = "上传成功";
  15.   break;
  16.   case 1:
  17.   msg = "上传的文件超过限制";
  18.   break;
  19.   case 2:
  20.   msg = "只能上传图片文件";
  21.   break;
  22.   default:
  23.   msg = "上传文件失败";
  24.   }
  25.   document.getElementById('processing').innerHTML = msg;
  26.   }
  27.   </script>
  28.   </head>
  29.   <body>
  30.   <div style="text-align:center">
  31.   <div id="processing"></div>
  32.   <form action="upload.php教程" method="post" enctype="multipart/form-data" target="form-target" onsubmit="startUpload();">
  33.   <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
  34.   <input type="file" name="myfile" />
  35.   <input type="submit" name="sub" value="upload" />
  36.   </form>
  37.   <iframe style="width:0; height:0; border:0;" name="form-target"></iframe>
  38.   </div>
  39.   </body>
  40.   </html>
  41.   php代码
  42.   <?php
  43.   sleep(2);
  44.   $fileTypes = array('jpg','png','gif','bmp');
  45.   $result = null;
  46.   $uploadDir = './upfiles';
  47.   $maxSize = 1 * pow(2,20);
  48.   if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['sub'])) {
  49.   $myfile = $_FILES['myfile'];
  50.   $myfileType = substr($myfile['name'], strrpos($myfile['name'], ".") + 1);
  51.   if ($myfile['size'] > $maxSize) {
  52.   $result = 1;
  53.   } else if (!in_array($myfileType, $fileTypes)) {
  54.   $result = 2;
  55.   } elseif (is_uploaded_file($myfile['tmp_name'])) {
  56.   $toFile = $uploadDir . '/' . $myfile['name'];
  57.   if (@move_uploaded_file($myfile['tmp_name'], $toFile)) {
  58.   $result = 0;
  59.   } else {
  60.   $result = -1;
  61.   }
  62.   } else {
  63.   $result = 1;
  64.   }
  65.   }
  66.   ?>
  67.   <script type="text/javascript">
  68.   window.top.window.stopUpload(<?php echo $result; ?>);
  69.   </script>
复制代码





欢迎光临 黑帽联盟 (https://bbs.cnblackhat.com/) Powered by Discuz! X2.5