php+iframe实现隐藏无刷新上传文件 程序员文章站 2022-07-11 08:01:25 首先ajax不能上传文件,这误导了我有段时间,今晚睡不着就照着说明做了个无刷新上传文件 其实原理很简单 复制代码 代码如下: 首先ajax不能上传文件,这误导了我有段时间,今晚睡不着就照着说明做了个无刷新上传文件 其实原理很简单 复制代码 代码如下: <form enctype="multipart/form-data" method="post" target="upload" action="http://localhost/class.upload.php" > <input type="file" name="uploadfile" /> <input type="submit" /> </form> <iframe name="upload" style="display:none"></iframe> 和一般的<form>标签相比多了一个target属性罢了,用于指定标签页在哪里打开以及提交数据。 如果没有设置该属性,就会像平常一样在本页重定向打开action中的url。 而如果设置为iframe的name值,即"upload"的话,就会在该iframe内打开,因为css设置为隐藏,因而不会有任何动静。若将display:none去掉,还会看到服务器的返回信息。 另外贴一下自己组织的类。 复制代码 代码如下: class upload { public $_file; public function __construct( $name =null) { if(is_null($name) || !isset($_files[$name])) $name = key($_files); if(!isset($_files[$name])) throw new exception("并没有文件上传"); $this->_file = $_files[$name]; if(!is_uploaded_file($this->_file['tmp_name'])) throw new exception("异常情况"); if($this->_file['error'] !== 0) throw new exception("错误代码:".$this->_file['error']); } public function moveto( $new_dir) { $real_dir = $this->checkdir($new_dir); return move_uploaded_file($this->_file['tmp_name'], $real_dir.'/'.$this->_file['name']); } private function checkdir($dir) { $real_dir = realpath($dir); if($real_dir === false) throw new exception("给定目录{$dir}不存在"); if(!is_writable($real_dir)) throw new exception("给定目录{$dir}不可写"); return $real_dir; }} 调用示例: 复制代码 代码如下: $inputname = 'uploadfile'; // 即<input type=“file" name="uploadfile" /> 中的name值,不填也行 $upload = new upload($inputname); $new_dir = "/www"; // 将文件移动到的路径 $upload->moveto($new_dir); 上一篇: 驱动程序无法使用安全套接字层(SSL)加密与 SQL Server 建立安全连接。错误: RSA premaster secret error 下一篇: PHP访问MYSQL数据库封装类(附函数说明) 推荐阅读 php+html5实现无刷新图片上传教程 使用PHP和HTML5 FormData实现无刷新文件上传教程 Thinkphp+smarty+uploadify实现无刷新上传 利用H5特性FormData实现不刷新文件上传 使用jQuery ajaxupload插件实现无刷新上传文件 ThinkPHP结合AjaxFileUploader实现无刷新文件上传的方法 ajax jsp 无刷新上传文件 JavaScript实现无刷新上传预览图片功能 php+iframe 实现上传文件功能示例 php+js实现的无刷新下载文件功能示例