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