Blogger Information
Blog 18
fans 0
comment 0
visits 13325
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
异常的重写、文件的上传、模型与数据表关联对应实现类与数据表的映射-2019-10-12
无聊了的博客
Original
592 people have browsed it

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());
}

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:作业没有写完整
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post