【www.gdgbn.com--其它】

其它原理很简单,利用form表单的target属性和iframe来实现的,打开为iframe试就行了,返回就利用js判断php教程运行后返回的参数是不是成功
一、上传文件的一个php方法。
该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失败,则返回空字符串。

php代码

    function uploadfile($file) {
        // 上传路径     $destinationpath = "./upload/";
        if (!file_exists($destinationpath)){
            mkdir($destinationpath , 0777);     }
        //重命名
        $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,该属性解释如下:
[pre]target属性:
_blank   ----------   新开窗口
_self   -----------   自身
_top   ------------   主框架
_parent   ---------   父框架
自定义名字     -----   出现于框架结构,将会在该名称的框架内打开链接

本例中采用iframe名字,所以表单在提交时会在iframe内打开链接(即无刷新,确切的说应该是
感觉无刷新)
在表单提交时,调用startupload方法,当然这是js定义的。
[/pre][pre]此外我们还定义一个span来显示提示信息。代码如下:
[/pre]xhtml代码

   

导入文件:
    <iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;">iframe>
    form> 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代码

    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;
      }

总结:方法很简单扼要,如果你以前没想到觉得ajax无刷新文件上传很难,现在明白利用iframe target来制作就觉得很容易了。

本文来源:http://www.gdgbn.com/luyouqishezhi/28803/