php+iframe implementation hide no refresh upload file

  • 2020-05-12 02:20:08
  • OfStack

First of all, ajax could not upload the file, which misled me for a period of time. I could not sleep tonight, so I followed the instructions and made an unrefreshed upload file

The principle is simple
 
<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> 

And one of < form > The tag has an target attribute that specifies where the TAB should be opened and where the data should be submitted.

If this property is not set, url in action is opened on this page as normal 1.

If the name value is set to iframe, "upload", it will be turned on inside that iframe, because CSS is set to hide, so nothing will happen. If you remove display:none, you will also see the return message from the server.

In addition, I will post a class organized by myself.
 
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(" No file is uploaded "); 

$this->_file = $_FILES[$name]; 

if(!is_uploaded_file($this->_file['tmp_name'])) 
throw new Exception(" Abnormal situation "); 
if($this->_file['error'] !== 0) 
throw new Exception(" The error code :".$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(" A given directory {$dir} There is no "); 
if(!is_writable($real_dir)) 
throw new Exception(" A given directory {$dir} Do not write "); 
return $real_dir; 
}} 

Call example:
 
$inputName = 'uploadfile'; 
//  namely <input type= " file" name="uploadfile" />  In the name I don't have to fill it in  
$upload = new upload($inputName); 
$new_dir = "/www"; //  The path to move the file to  
$upload->moveTo($new_dir); 

Related articles: