首先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)
- {//開源代碼Vevb.com
- $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);
新聞熱點
疑難解答