1、写一个异常的实现上传文件
实例
<!--upload.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传附件</title> </head> <body> <form action="index.php" method="post" enctype="multipart/form-data"> <input type="file" name="my_file" value="选择文件"> <button>上传</button> </form> </body> </html> <!--//index.php--> <?php namespace _1012; use Exception; class UploadException extends Exception { public function __construct($message = "", $code = 0, Throwable $previous = null) { parent::__construct($message, $code, $previous); } public function errInfo(){ $result = [ 'code'=>$this->getCode(), 'message'=>$this->getMessage() ]; return $result; } } try{ $fileExt = ["jpg","png","jpeg"]; $file = $_FILES["my_file"]; $fileName = $file["name"]; $tmpName = $file["tmp_name"]; $newPath = __DIR__.'/img/'; $errCode = $file["error"]; if($errCode>0){ switch ($errCode){ case 1: case 2: throw new UploadException('上传文件多大','104'); case 3: throw new UploadException('文件上传不完整','105'); case 4: throw new UploadException('没有文件上传','106'); default: throw new UploadException('未知错误','107'); } } $fileType = explode('/',$file["type"])[1]; $newFileName = time().'_'.mt_rand().'.'.explode('.',$fileName)[1]; if(!in_array($fileType,$fileExt)){ throw new UploadException('文件类型不符','101'); } if(is_uploaded_file1($tmpName)){ if(move_uploaded_file($tmpName,$newPath.$newFileName)){ echo '<script>alert("上传成功")</script>'; }else{ throw new UploadException('文件无法移动到指定目录请检查权限','102'); } }else{ throw new UploadException('非法上传','103'); } }catch (UploadException $e){ print_r($e->errInfo()); }
运行实例 »
点击 "运行实例" 按钮查看在线实例