php iframe 无刷新文件上传代码

原理很简单,利用form表单的target属性和iframe来实现的,打开为iframe试就行了,返回就利用js判断php教程运行后返回的参数是不是成功.

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

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

  1. function uploadfile($file) {
  2. // 上传路径 $destinationpath = "./upload/";
  3. if (!file_exists($destinationpath)){
  4. mkdir($destinationpath , 0777); }
  5. //重命名
  6. $filename = date('ymdhis') . '_' . iconv('utf-8' , 'gb2312' , basename($file['name']));
  7. if (move_uploaded_file($file['tmp_name'], $destinationpath . $filename)) { return iconv('gb2312' , 'utf-8' , $filename);
  8. } return '';
  9. }

二、客户端html代码

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

target属性:_blank:新开窗口,_self:自身,_top:主框架,_parent:父框架,自定义名字:出现于框架结构,将会在该名称的框架内打开链接,本例中采用iframe名字,所以表单在提交时会在iframe内打开链接(即无刷新,确切的说应该是感觉无刷新),在表单提交时,调用startupload方法,当然这是js定义的。

此外我们还定义一个span来显示提示信息,代码如下:
  1. <form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startupload()"> 导入文件:<input type="file" name="myfile" />
  2. <input type="submit" name="submitbtn" value="导入" /> <iframe name="upload_target" src="#" >iframe>
  3. form> <span >span>

三、js部分

这部分比较简单,只是显示提示信息

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

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

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

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

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