好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

php无刷新利用iframe实现页面无刷新上传文件 - p

php无刷新利用iframe实现页面无刷新上传文件

利用form表单的target属性和iframe

一、上传文件的一个php方法

该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失败,则返回空字符串,php代码如下:

function  uploadfile( $file ) {              // 上传路径     $destinationpath = "./upload/";             if  (! file_exists ( $destinationpath )){                mkdir ( $destinationpath  , 0777);     }               //开源代码phpfensi.com            //重命名            $filename  =  date ( 'ymdhis' ) .  '_'  . iconv( 'utf-8'  ,  'gb2312'  ,  basename ( $file [ 'name' ]));            if  (move_uploaded_file( $file [ 'tmp_name' ],  $destinationpath  .  $filename )) {          return  iconv( 'gb2312'  ,  'utf-8'  ,  $filename );           }      return   '' ;         } 

二、客户端html代码

这里正是技巧所在,添加另一个iframe来实现,表单标签form定义了一个属性target,该属性解释如下.

target属性:

_blank   ----------   新开窗口

_self   -----------   自身

_top   ------------   主框架

_parent   ---------   父框架

自定义名字  -----  出现于框架结构,将会在该名称的框架内打开链接.

本例中采用iframe名字,所以表单在提交时会在iframe内打开链接,即无刷新,确切的说应该是感觉无刷新.

在表单提交时,调用startupload方法,当然这是js定义的,此外我们还定义一个span来显示提示信息,代码如下:

< form   id = "upform"   action = "upload.php"   method = "post"   enctype = "multipart/form-data"   target = "upload_target"   onsubmit = "startupload()" >  导入文件: < input   type = "file"   name = "myfile"   id = "myfile"   />        < input   type = "submit"   name = "submitbtn"   value = "导入"   />   < iframe   id = "upload_target"   name = "upload_target"   src = "#"   style = "width:0;height:0;border:0px solid #fff;" > iframe >       form >   < span   id = "info" > span >  

三、js部分

这部分比较简单,只是显示提示信息,实例代码如下:

function  startupload() {            var  spanobj = document.getelementbyid( "info" );     spanobj.innerhtml =  " 开始上传" ;       }        function  stopupload(responsetext){      var  spanobj = document.getelementbyid( "info" );           spanobj.innerhtml = " 上传成功;     spanobj.innerhtml = responsetext;         }  

接下来就要看服务器端得处理了.

四、服务器段处理部分,php代码如下:

$file  =  $_files [ 'myfile' ];    $filename  = uploadfile( $file );          $result  = readfromfile( "./upload/"  .  $filename );  此外在后面还应该加上一句js代码用来调用stopupload方法。  javascript代码        window.top.window.stopupload( "" );  最后在补上php中的readfromfile方法,就大功告成了。  php代码  //开源代码phpfensi.com        function  readfromfile( $target_path ) {            // 读取文件内容     $file = fopen($target_path,'r') or die("unable to open file");             $filecontent  =  '' ;      while (! feof ( $file ))           {          $str  =  fgets ( $file );                $filecontent  .=  $str ;     }           fclose( $file );      return   $filecontent ;         }

查看更多关于php无刷新利用iframe实现页面无刷新上传文件 - p的详细内容...

  阅读:72次