php文件上传简单封装

下面贴上php文件上传的示例

	/**
	 * Class getFiles 文件上传
	 */
	class getFiles
	{
	    private $file;
	    private $thisType;
	
	
	    function __construct($file)
	    {
	        $this->file = $file;
	        $this->thisType = NULL;
	        $this->verifyFile();
	        $this->moveFile();
	    }
	
	
	    /**
	     *  验证文件
	     */
	    public function verifyFile()
	    {
	        try {
	            $maxSize = 2 * 1024 * 1024;
	            if ($maxSize < $this->file['size']) {
	                die('文件大于上传限制,请选择小于2M的文件重新尝试上传');
	            }
	
	            $type = array(
	                '.png' => 'image/png',
	                '.jpg' => 'image/jpg',
	                '.jpeg' => 'image/jpeg',
	                '.gif' => 'image/gif'
	            );
	
	
	            foreach ($type as $key => $value) {
	
	                if ($value == $this->file['type']) {
	                    $this->thisType = $key;
	                    break;
	                }
	            }
	            if (!$this->thisType) {
	                echo 'File type not supported';
	                return;
	            }
	        } catch (Exception $e) {
	            echo $e->getMessage();
	        }
	    }
		/**
	     *  移动文件返回路径
	     */
	    public function moveFile()
	    {
	        try {
	
	            $filename = 'uploadimage/' . time() . $this->thisType;
	            if (file_exists($filename)) {
	                echo "File Exist";
	                return;
	            }
	
	           $res= move_uploaded_file($this->file['tmp_name'], $filename);
	            if($res){
	                echo json_encode($filename);
	                return;
	            }
	            echo 'Move File Error';
	        } catch (Exception $e) {
	            echo $e->getMessage();
	        }
	
	    }
	    /**
	     * 释放资源
	     */
	    public function __destruct(){
	        $this->file= null;
	        $this->thisType= null;
    	}
	}

猜你喜欢

转载自blog.csdn.net/qq_39043923/article/details/88685188
今日推荐