Blogger Information
Blog 40
fans 0
comment 0
visits 37563
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP学习总结(18)异常类在Upload中的运用——2019年10月12日20:00分
虎子爸爸
Original
973 people have browsed it

upload-1.png

上码:

<?php

namespace Upload;

use Exception;

use think\Error;



// 将系统的异常类进行扩展,自定义

class CalException extends Exception{

    public function __construct($message = "",$code = 0)  {

        parent::__construct($message,$code);

    }

    public function errorInfo(){

        return <<<ERROR

        <h2>

                <strong>{$this->getCode()}: </strong>

                <span style="color: red;">{$this->getMessage()}</span>

                </h2>


ERROR;//【注意这里】        

    }

}

//注意这里

try{

    class upload{

        //先设定允许上传的文件类型

        private $allow_types=array('image/jpeg','image/pjpeg','image/png','image/x-png');

        //设定允许上传的最大文件

        private $max_size=8576;  //1048576===1M

        //设定文件在服务器的存储位置,

        private $upload_path='./';

        //保存上传文件发送错误时的错误信息。通过查看该属性,可以知道上传失败的原因

        private $error = '';

        

        //上传方法

        public function up($file,$prefix=''){

            //第一步:先判断有没有上传,有没有上传错误

            if($file['error'] != 0){  

                $upload_errors=array(   //先定义一个错误数组

                1=>'文件太大,超出限制',

                2=>'文件太大,超出限制',

                3=>'文件没有上传完',

                4=>'文件没有上传',

                6=>'没有找到临时上传目录',

                7=>'临时文件写入失败'                   

                );

                $this->error = isset($upload_errors[$file['error']]) ? $upload_errors[$file['error']] : '未知错误';

                return false;

            }

            //第二步:判断文件类型是否存在于数组中

            if(!in_array($file['type'],$this->allow_types)){

                //如果不存在,就更新属性$error,把相关错误信息赋值给该属性,最后返回false

                //$this->error = '文件类型错误,允许的类型为:'***plode('|',$this->allow_types);

                throw new CalException('文件类型错误', 101);

                return false;

            }

            //第三步:判断文件大小

            if($file['size'] > $this->max_size){

                //$this->error = '文件不能大于'.$this->max_size.'字节';

                throw new CalException('文件太大', 102);

                return false;

            }

            $new_file = uniqid($prefix).strrchr($file['name'],'.');

            $sub_path=date('Ymdh');

            $upload_path = $this->upload_path.$sub_path;

            //判断这个目录是否存在

            if(!is_dir($upload_path)){

                //假如不存在,就创建该目录

                mkdir($upload_path);

            }

            //移动文件

            if(move_uploaded_file($file['tmp_name'],$upload_path.'/'.$new_file)){

                return $sub_path.'/'.$new_file;

            }

            else{

                // $this->error='移动失败';

                throw new CalException('移动失败', 103);

                return false;

            }

        }

        public function getError(){

            return $this->error;

        }

    }

    //注意这里,只能放在try里面

    if(isset($_FILES['pic'])){

        $upload = new \Upload\upload;

        if(!($pic_path=$upload->up($_FILES['pic'],'user_'))){

            echo $upload->getError();

            die;

        }else{

            echo '<script>alert("上传成功");history.back();</script>';

        }

    }

}catch (CalException $e) {

    echo $e->errorInfo();

    echo '<br>';

    //echo $e->getCode(), ':   ' , $e->getMessage();

}


?>


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

</head>

<body>

    <form action="#" method="post" enctype="multipart/form-data">

      <p>上传文件:<input type="file" name="pic"></p>

      <p><input type="submit" value="上传"></p>

    </form>

</body>

</html>

总结:感觉还是蛮复杂的,不像我想象中简单!

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