主頁 > 後端開發 > 檔案上傳和下載實體原始碼

檔案上傳和下載實體原始碼

2020-09-20 02:11:04 後端開發

效果圖

首先是封裝好的圖片類(縮放及生成水印)

GDBasic.php

<?php
/**
 * GDBasic.php
 * description GD基礎類
 */

namespace test\Lib;


class GDBasic
{
    protected static $_check =false;

    //檢查服務器環境中gd庫
    public static function check()
    {
        //當靜態變數不為false
        if(static::$_check)
        {
            return true;
        }

        //檢查gd庫是否加載
        if(!function_exists("gd_info"))
        {
            throw new \Exception('GD is not exists');
        }

        //檢查gd庫版本
        $version = '';
        $info = gd_info();
        if(preg_match("/\\d+\\.\\d+(?:\\.\\d+)?/", $info["GD Version"], $matches))
        {
            $version = $matches[0];
        }

        //當gd庫版本小于2.0.1
        if(!version_compare($version,'2.0.1','>='))
        {
            throw new \Exception("GD requires GD version '2.0.1' or greater, you have " . $version);
        }

        self::$_check = true;
        return self::$_check;
    }
}

Image.php

 

<?php
/**
 * Image.php
 * description 影像類
 */

namespace test\Lib;

require_once 'GDBasic.php';

class Image extends GDBasic
{
    protected $_width;
    protected $_height;
    protected $_im;
    protected $_type;
    protected $_mime;
    protected $_real_path;

    
    public function __construct($file)
    {
        //檢查GD庫
        self::check();
        $imageInfo = $this->createImageByFile($file);
        $this->_width = $imageInfo['width'];
        $this->_height = $imageInfo['height'];
        $this->_im = $imageInfo['im'];
        $this->_type = $imageInfo['type'];
        $this->_real_path = $imageInfo['real_path'];
        $this->_mime = $imageInfo['mime'];
    }


    /**
     * 根據檔案創建影像
     * @param $file
     * @return array
     * @throws \Exception
     */
    public function createImageByFile($file)
    {
        //檢查檔案是否存在
        if(!file_exists($file))
        {
            throw new \Exception('file is not exits');
        }

        //獲取影像資訊
        $imageInfo = getimagesize($file);
        $realPath = realpath($file);
        if(!$imageInfo)
        {
            throw new \Exception('file is not image file');
        }

        switch($imageInfo[2])
        {
            case IMAGETYPE_GIF:
                $im = imagecreatefromgif($file);
                break;
            case IMAGETYPE_JPEG:
                $im = imagecreatefromjpeg($file);
                break;
            case IMAGETYPE_PNG:
                $im = imagecreatefrompng($file);
                break;
            default:
                throw  new \Exception('image file must be png,jpeg,gif');
        }

        return array(
            'width'     => $imageInfo[0],
            'height'    => $imageInfo[1],
            'type'      => $imageInfo[2],
            'mime'      => $imageInfo['mime'],
            'im'        => $im,
            'real_path' => $realPath,
        );

    }

    /**
     * 縮略圖
     * @param  int $width 縮略圖高度
     * @param  int $height 縮略圖寬度
     * @return $this
     * @throws \Exception
     */
    public function resize($width, $height)
    {
        if(!is_numeric($width) || !is_numeric($height))
        {
            throw new \Exception('image width or height must be number');
        }
        //根據傳參的寬高獲取最終影像的寬高
        $srcW = $this->_width; 
        $srcH = $this->_height;

        if($width <= 0 || $height <= 0)
        {
            $desW = $srcW;//縮略圖高度
            $desH = $srcH;//縮略圖寬度
        }
        else
        {
            $srcP = $srcW / $srcH;//寬高比
            $desP = $width / $height; 

            if($width > $srcW)
            {
                if($height > $srcH)
                {
                    $desW = $srcW;
                    $desH = $srcH;
                }
                else
                {
                    $desH = $height;
                    $desW = round($desH * $srcP);
                }
            }
            else
            {
                if($desP > $srcP)
                {
                    $desW = $width;
                    $desH = round($desW / $srcP);
                }
                else
                {
                    $desH = $height;
                    $desW = round($desH * $srcP);
                }
            }
        }

        //PHP版本小于5.5
        if(version_compare(PHP_VERSION, '5.5.0', '<'))
        {
            $desIm = imagecreatetruecolor($desW, $desH);
            if(imagecopyresampled($desIm, $this->_im, 0, 0, 0, 0, $desW, $desH, $srcW, $srcH))
            {
                imagedestroy($this->_im);
                $this->_im = $desIm;
                $this->_width = imagesx($this->_im);
                $this->_height = imagesy($this->_im);
            }
        }
        else
        {
            if($desIm = imagescale($this->_im, $desW, $desH))
            {
                $this->_im = $desIm;
                $this->_width = imagesx($this->_im);
                $this->_height = imagesy($this->_im);
            }

        }

        return $this;
    }


    /**
     * 根據百分比生成縮略圖
     * @param int $percent 1-100
     * @return Image
     * @throws \Exception
     */
    public function resizeByPercent($percent)
    {
        if(intval($percent) <= 0)
        {
            throw new \Exception('percent must be gt 0');
        }

        $percent = intval($percent) > 100 ? 100 : intval($percent);

        $percent = $percent / 100;

        $desW = $this->_width * $percent;
        $desH = $this->_height * $percent;
        return $this->resize($desW, $desH);
    }


    /**
     * 影像旋轉
     * @param $degree
     * @return $this
     */
    public function rotate($degree)
    {
        $degree = 360 - intval($degree);
        $back = imagecolorallocatealpha($this->_im,0,0,0,127);
        $im = imagerotate($this->_im,$degree,$back,1);
        imagesavealpha($im,true);
        imagedestroy($this->_im);
        $this->_im = $im;
        $this->_width = imagesx($this->_im);
        $this->_height = imagesy($this->_im);
        return $this;
    }


    /**
     * 生成水印
     * @param file $water 水印圖片
     * @param int $pct   透明度
     * @return $this
     */
    public function waterMask($water ='',$pct = 60 )
    {
        //根據水印影像檔案生成影像資源
        $waterInfo = $this->createImageByFile($water);
        imagecopymerge();
        //銷毀$this->_im
        $this->_im = $waterInfo['im'];
        $this->_width = imagesx($this->_im);
        $this->_height = imagesy($this->_im);
        return $this;

    }



    /**
     * 圖片輸出
     * @return bool
     */
    public function show()
    {
        header('Content-Type:' . $this->_mime);
        if($this->_type == 1)
        {
            imagegif($this->_im);
            return true;
        }

        if($this->_type == 2)
        {
            imagejpeg($this->_im, null, 80);
            return true;
        }

        if($this->_type == 3)
        {
            imagepng($this->_im);
            return true;
        }
    }

    /**
     * 保存影像檔案
     * @param $file
     * @param null $quality
     * @return bool
     * @throws \Exception
     */
    public function save($file, $quality = null)
    {
        //獲取保存目的檔案的擴展名
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        $ext = strtolower($ext);
        if(!$ext || !in_array($ext, array('jpg', 'jpeg', 'gif', 'png')))
        {
            throw new \Exception('image save file must be jpg ,png,gif');
        }

        if($ext === 'gif')
        {
            imagegif($this->_im, $file);
            return true;
        }
        if($ext === 'jpeg' || $ext === 'jpg')
        {
            if($quality > 0)
            {
                if($quality < 1)
                {
                    $quality = 1;
                }
                if($quality > 100)
                {
                    $quality = 100;
                }

                imagejpeg($this->_im, $file, $quality);
            }
            else
            {
                imagejpeg($this->_im, $file);
            }
            return true;
        }

        if($ext === 'png')
        {
            imagepng($this->_im, $file);
            return true;
        }

    }
}

style樣式不是重點,先不放了

然后是ajax類封裝的檔案 ajax.js

let $ = new class {

    constructor()
    {
        this.xhr = new XMLHttpRequest();
        this.xhr.onreadystatechange = () => {
            if (this.xhr.readyState == 4 && this.xhr.status == 200) {
                // process response text
                let response = this.xhr.responseText;
                if (this.type == "json") {
                    response = JSON.parse(response);
                }
                this.callback(response);
            }
        }
    }

    get(url, parameters, callback, type = "text")
    {
        // url = test.php?username=zhangsan&age=20
        // parameters = {"username": "zhangsan", "age": 20}
        let data = https://www.cnblogs.com/chenyingying0/p/this.parseParameters(parameters);
        if (data.length > 0) {
            url += "?" + data;
        }
        this.type = type;
        this.callback = callback;
        this.xhr.open("GET", url, true);
        this.xhr.send();
    }

    post(url, parameters, callback, type = "text")
    {
        let data = this.parseParameters(parameters);
        this.type = type;
        this.callback = callback;
        this.xhr.open("POST", url, true);
        this.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        this.xhr.send(data);
    }

    parseParameters(parameters)
    {
        // username=zhangsan&age=20
        let buildStr = "";
        for (let key in parameters) {
            let str = key + "=" + parameters[key];
            buildStr += str + "&";
        }
        return buildStr.substring(0, buildStr.length - 1);
    }
};

首頁檔案index.php

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3個meta標簽*必須*放在最前面,任何其他內容都*必須*跟隨其后! -->
    <title>檔案上傳和下載</title>
    <!-- Bootstrap -->
    <link href="https://www.cnblogs.com/chenyingying0/p/style/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://www.cnblogs.com/chenyingying0/p/style/css/site.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
        .projects .thumbnail .caption {
            height: auto;
            max-width: auto;
        }
        .image{
            margin:10px auto;
            border-radius:5px;
            overflow:hidden;
            border:1px solid #CCC;
        }
        .image .caption P{
            text-align: center;
        }
    </style>
</head>

<body>
    <!--導航欄-->
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target=".navbar-collapse">
                  <span class="sr-only">Toggle navigation</span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand hidden-sm" href="" onclick="_hmt.push(['_trackEvent', 'navbar', 'click', 'navbar-首頁'])">XX網</a>
            </div>
            <div class="navbar-collapse collapse" role="navigation">
                <ul class="nav navbar-nav">
                    <li class="hidden-sm hidden-md">
                        <a href="" target="_blank"></a>
                    </li>
                    <li>
                        <a href="" target="_blank"></a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <!--導航欄結束-->
    <!--巨幕-->
    <div class="jumbotron masthead">
        <div class="container">
            <h1>檔案上傳下載</h1>
            <h2>實作檔案的上傳和下載功能</h2>
            <p class="masthead-button-links">
                <form class="form-inline" onsubmit="return false;">
                    <div class="form-group">
                        <input type="search" class="form-control keywords" id="exampleInputName2" placeholder="輸入搜索內容" name="keywords" value="">
                        <button class="btn btn-default searchBtn" type="submit">搜索</button>
                        <button type="button" class="btn btn-primary btn-default" data-toggle="modal" data-target="#myModal">  上傳  </button>
                    </div>
                </form>
            </p>
        </div>
    </div>
    <!--巨幕結束-->
    <!-- 模態框 -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <form class="form-inline" action="upload_class.php" method="post" enctype="multipart/form-data">
                <input type="hidden" name="MAX_FILE_SIZE" value="https://www.cnblogs.com/chenyingying0/p/10240000" />
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">上傳圖片</h4>
                    </div>
                    <div class="modal-body">
                        <p>選擇圖片:</p><input type="file" id="image" name="test_pic[]">
                        <br/>
                        <p>圖片描述:</p><textarea class="form-control" cols="75" name="description" id="info"></textarea>
                        <br/><br/>
                        <p>
                          是否添加水印:
                          <select name="mark">
                            <option value="https://www.cnblogs.com/chenyingying0/p/1">添加</option>
                            <option value="https://www.cnblogs.com/chenyingying0/p/0">不添加</option>
                          </select>
                        </p>
                        <br/>
                        <p>
                          圖片寬度比例:
                            <select name="scale">
                              <option value="https://www.cnblogs.com/chenyingying0/p/800*600">800*600</option>
                              <option value="https://www.cnblogs.com/chenyingying0/p/600*450">600*450</option>
                              <option value="https://www.cnblogs.com/chenyingying0/p/400*300">400*300</option>
                            </select>
                        </p>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-default" name="submit" id="submit" onclick="show(this)">上傳</button>
                        <button type="reset" class="btn btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <!--模態框結束-->

    <div class="container projects">
        <div class="projects-header page-header">
            <h2>上傳圖片展示</h2>
            <p>將上傳的圖片展示在頁面中</p>
        </div>
        <div class="row pic_body">
            <!-- 使用js顯示圖片 -->
        </div>
        <!--分頁-->
        <nav aria-label="Page navigation" style="text-align:center">
            <ul class="pagination pagination-lg">
                <!-- 使用js顯示頁碼 -->
            </ul>
        </nav>
    </div>

    <footer class="footer  container">
        <div class="row footer-bottom">
            <ul class="list-inline text-center">
                <h4><a href="https://www.cnblogs.com/chenyingying0/p/class.test.com" target="_blank">class.test.com</a> | XX網</h4>
            </ul>
        </div>
    </footer>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://www.cnblogs.com/chenyingying0/p/style/js/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://www.cnblogs.com/chenyingying0/p/style/js/bootstrap.min.js"></script>
    <script type="text/JavaScript">
        function show(){
          if(document.getElementById("image").value =https://www.cnblogs.com/chenyingying0/p/= ''){
            alert('請選擇圖片');
          }
          if(document.getElementById("info").value =https://www.cnblogs.com/chenyingying0/p/= ''){
            alert('請輸入圖片描述');
          }
        }
    </script>
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <script src="https://www.cnblogs.com/chenyingying0/p/style/js/Ajax.js"></script>
    <script>
        let pageNo = 1;
        let kws = '';
        let searchBtn = document.getElementsByClassName('searchBtn')[0];
        searchBtn.onclick = function() {
            let search = document.getElementsByClassName('keywords')[0];
            let keywords = search.value;
            requestData(pageNo, keywords);
            kws = keywords;
        };

        let requestPage = function(page) {
            requestData(page, kws);
            pageNo = page;
        };


        let requestData = https://www.cnblogs.com/chenyingying0/p/function(page_number, keywords) {
            let pagination = document.getElementsByClassName('pagination')[0];
            let pic_body = document.getElementsByClassName('pic_body')[0];
            pic_body.innerHTML = '<p style="text-align:center"><i class="fa fa-spinner fa-spin" style="font-size:24px"></i> 加載中...</p>';
            $.get('search.php', {"page": page_number, "keywords": keywords}, function (res) {
                let divs = '';
                if (res.code == 1) {
                    // 請求成功
                    res.rows.forEach(function (item) {
                        let div = '<div class="col-sm-6 col-md-3 col-lg-4"><div class="image"><a href="' + item.path + '" target="_blank"><img class="img-responsive" src="' + item.path + '" ></a><div class="caption"><p>' + item.info + '</p></div></div></div>';
                        divs += div;
                    });
                    pic_body.innerHTML = divs;


                    // 加載頁碼導航
                    // previous
                    let previousBtn = '';
                    if (res.page_number == 1) {
                        previousBtn = '<li class="page-item disabled"><a class="page-link" href="javascript:requestPage(' + (res.page_number - 1) + ');">Previous</a></li>';
                    } else {
                        previousBtn = '<li class="page-item"><a class="page-link" href="javascript:requestPage(' + (res.page_number - 1) + ');">Previous</a></li>';
                    }
                    // next
                    let nextBtn = '';
                    if (res.page_total == res.page_number) {
                        nextBtn = '<li class="page-item disabled"><a class="page-link" href="javascript:requestPage(' + (res.page_number + 1) + ');">Next</a></li>';
                    } else {
                        nextBtn = '<li class="page-item"><a class="page-link" href="javascript:requestPage(' + (res.page_number + 1) + ');">Next</a></li>'
                    }

                    let pages = previousBtn;
                    for (let page = 1; page <= res.page_total; page++) {
                        let active = '';
                        if (page == res.page_number) {
                            active = 'active';
                        }
                        pages += '<li class="page-item ' + active + '"><a class="page-link" href="javascript:requestPage(' + page + ');">' + page + '</a></li>';
                    }
                    pages += nextBtn;
                    pagination.innerHTML = pages;
                }   
            },'json');
        };
        requestData(1, '');
    </script>
</body>
</html>

圖片相關功能處理 upload_class.php

<?php

//接收傳過來的資料
$description=$_POST['description'];//描述
$mark=$_POST['mark'];//水印
$scale=$_POST['scale'];//比例 800*600
$path='';//圖片存盤路徑


//根據比例獲取寬高
$width=substr($scale,0,3);//800
$height=substr($scale,4,3);//600


//上傳圖片并存盤
require('UploadFile.php');

$upload = new UploadFile('test_pic');
$upload->setDestinationDir('./uploads');
$upload->setAllowMime(['image/jpeg', 'image/gif','image/png']);
$upload->setAllowExt(['gif', 'jpeg','jpg','png']);
$upload->setAllowSize(2*1024*1024);
if ($upload->upload()) {
    $filename=$upload->getFileName()[0];
    $dir=$upload->getDestinationDir();
    $path=$dir.'/'.$filename;//圖片存盤的實際路徑
    
} else {
    var_dump($upload->getErrors());
}


//根據比例調整影像
require_once './lib/Image.php';
$image = new \test\Lib\Image($path);
//放大并保存
$image->resize($width,$height)->save($path);

$info = getimagesize($path);
//根據不同的影像type 來創建影像
switch($info[2])
{
    case 1://IMAGETYPE_GIF
        $image = imagecreatefromgif($path);
        break;
    case IMAGETYPE_JPEG:
        $image = imagecreatefromjpeg($path);
        break;
    case 3:
        $image = imagecreatefrompng($path);
        break;

    default:
        echo '影像格式不支持';
        break;

}
    
//添加水印
if($mark==1){

    $logo=imagecreatefrompng('./uploads/logo.png');
    //添加水印
    imagecopy($image,$logo,0,0,0,0,imagesx($logo),imagesy($logo));
    //header('Content-type:image/png');
    imagejpeg($image,$path);
}

$dst_image=imagecreatetruecolor($width,$height);
//拷貝源影像左上角起始
imagecopy( $dst_image, $image, 0, 0, 0, 0, $width, $height );
imagejpeg($dst_image,$path);

//存入資料庫
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "pic";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 設定 PDO 錯誤模式,用于拋出例外
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO pic(`path`, `mark`, `scale`,`info`)
VALUES ('$path', '$mark', '$scale','$description')";
// 使用 exec() ,沒有結果回傳
$conn->exec($sql);
    exit("<script>alert(\"圖片上傳成功!\");window.location=\"index.php\";</script>");
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}

封裝好的檔案上傳類 UploadFile.php

<?php
/**
 * Created by PhpStorm.
 * User: JasonLee
 * Date: 2018/11/11
 * Time: 22:01
 */

class UploadFile
{

    /**
     *
     */
    const UPLOAD_ERROR = [
        UPLOAD_ERR_INI_SIZE => '檔案大小超出了php.ini當中的upload_max_filesize的值',
        UPLOAD_ERR_FORM_SIZE => '檔案大小超出了MAX_FILE_SIZE的值',
        UPLOAD_ERR_PARTIAL => '檔案只有部分被上傳',
        UPLOAD_ERR_NO_FILE => '沒有檔案被上傳',
        UPLOAD_ERR_NO_TMP_DIR => '找不到臨時目錄',
        UPLOAD_ERR_CANT_WRITE => '寫入磁盤失敗',
        UPLOAD_ERR_EXTENSION => '檔案上傳被擴展阻止',
    ];

    /**
     * @var
     */
    protected $field_name;

    /**
     * @var string
     */
    protected $destination_dir;

    /**
     * @var array
     */
    protected $allow_mime;

    /**
     * @var array
     */
    protected $allow_ext;

    /**
     * @var
     */
    protected $file_org_name;

    /**
     * @var
     */
    protected $file_type;

    /**
     * @var
     */
    protected $file_tmp_name;

    /**
     * @var
     */
    protected $file_error;

    /**
     * @var
     */
    protected $file_size;

    /**
     * @var array
     */
    protected $errors;

    /**
     * @var
     */
    protected $extension;

    /**
     * @var
     */
    protected $file_new_name;

    /**
     * @var float|int
     */
    protected $allow_size;

    /**
     * UploadFile constructor.
     * @param $keyName
     * @param string $destinationDir
     * @param array $allowMime
     * @param array $allowExt
     * @param float|int $allowSize
     */
    public function __construct($keyName, $destinationDir = './uploads', $allowMime = ['image/jpeg', 'image/gif'], $allowExt = ['gif', 'jpeg'], $allowSize = 2*1024*1024)
    {
        $this->field_name = $keyName;
        $this->destination_dir = $destinationDir;
        $this->allow_mime = $allowMime;
        $this->allow_ext = $allowExt;
        $this->allow_size = $allowSize;
    }

    /**
     * @param $destinationDir
     */
    public function setDestinationDir($destinationDir)
    {
        $this->destination_dir = $destinationDir;
    }

    /**
     * @param $allowMime
     */
    public function setAllowMime($allowMime)
    {
        $this->allow_mime = $allowMime;
    }

    /**
     * @param $allowExt
     */
    public function setAllowExt($allowExt)
    {
        $this->allow_ext = $allowExt;
    }

    /**
     * @param $allowSize
     */
    public function setAllowSize($allowSize)
    {
        $this->allow_size = $allowSize;
    }

    /**
     * @return bool
     */
    public function upload()
    {
        // 判斷是否為多檔案上傳
        $files = [];
        if (is_array($_FILES[$this->field_name]['name'])) {
            foreach($_FILES[$this->field_name]['name'] as $k => $v) {
                $files[$k]['name'] = $v;
                $files[$k]['type'] = $_FILES[$this->field_name]['type'][$k];
                $files[$k]['tmp_name'] = $_FILES[$this->field_name]['tmp_name'][$k];
                $files[$k]['error'] = $_FILES[$this->field_name]['error'][$k];
                $files[$k]['size'] = $_FILES[$this->field_name]['size'][$k];
            }
        } else {
            $files[] = $_FILES[$this->field_name];
        }

        foreach($files as $key => $file) {
            // 接收$_FILES引數
            $this->setFileInfo($key, $file);

            // 檢查錯誤
            $this->checkError($key);

            // 檢查MIME型別
            $this->checkMime($key);

            // 檢查擴展名
            $this->checkExt($key);

            // 檢查檔案大小
            $this->checkSize($key);

            // 生成新的檔案名稱
            $this->generateNewName($key);

            if (count((array)$this->getError($key)) > 0) {
                continue;
            }
            // 移動檔案
            $this->moveFile($key);
        }
        if (count((array)$this->errors) > 0) {
            return false;
        }
        return true;
    }

    /**
     * @return array
     */
    public function getErrors()
    {
        return $this->errors;
    }

    /**
     * @param $key
     * @return mixed
     */
    protected function getError($key)
    {
        return $this->errors[$key];
    }

    /**
     *
     */
    protected function setFileInfo($key, $file)
    {
        // $_FILES  name type temp_name error size
        $this->file_org_name[$key] = $file['name'];
        $this->file_type[$key] = $file['type'];
        $this->file_tmp_name[$key] = $file['tmp_name'];
        $this->file_error[$key] = $file['error'];
        $this->file_size[$key] = $file['size'];
    }


    /**
     * @param $key
     * @param $error
     */
    protected function setError($key, $error)
    {
        $this->errors[$key][] = $error;
    }


    /**
     * @param $key
     * @return bool
     */
    protected function checkError($key)
    {
        if ($this->file_error > UPLOAD_ERR_OK) {
            switch($this->file_error) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                case UPLOAD_ERR_PARTIAL:
                case UPLOAD_ERR_NO_FILE:
                case UPLOAD_ERR_NO_TMP_DIR:
                case UPLOAD_ERR_CANT_WRITE:
                case UPLOAD_ERR_EXTENSION:
                    $this->setError($key, self::UPLOAD_ERROR[$this->file_error]);
                    return false;
            }
        }
        return true;
    }


    /**
     * @param $key
     * @return bool
     */
    protected function checkMime($key)
    {
        if (!in_array($this->file_type[$key], $this->allow_mime)) {
            $this->setError($key, '檔案型別' . $this->file_type[$key] . '不被允許!');
            return false;
        }
        return true;
    }


    /**
     * @param $key
     * @return bool
     */
    protected function checkExt($key)
    {
        $this->extension[$key] = pathinfo($this->file_org_name[$key], PATHINFO_EXTENSION);
        if (!in_array($this->extension[$key], $this->allow_ext)) {
            $this->setError($key, '檔案擴展名' . $this->extension[$key] . '不被允許!');
            return false;
        }
        return true;
    }

    /**
     * @return bool
     */
    protected function checkSize($key)
    {
        if ($this->file_size[$key] > $this->allow_size) {
            $this->setError($key, '檔案大小' . $this->file_size[$key] . '超出了限定大小' . $this->allow_size);
            return false;
        }
        return true;
    }


    /**
     * @param $key
     */
    protected function generateNewName($key)
    {
        $this->file_new_name[$key] = uniqid() . '.' . $this->extension[$key];
    }


    /**
     * @param $key
     * @return bool
     */
    protected function moveFile($key)
    {
        if (!file_exists($this->destination_dir)) {
            mkdir($this->destination_dir, 0777, true);
        }
        $newName = rtrim($this->destination_dir, '/') . '/' . $this->file_new_name[$key];
        if (is_uploaded_file($this->file_tmp_name[$key]) && move_uploaded_file($this->file_tmp_name[$key], $newName)) {
            return true;
        }
        $this->setError($key, '上傳失敗!');
        return false;
    }

    /**
     * @return mixed
     */
    public function getFileName()
    {
        return $this->file_new_name;
    }

    /**
     * @return string
     */
    public function getDestinationDir()
    {
        return $this->destination_dir;
    }

    /**
     * @return mixed
     */
    public function getExtension()
    {
        return $this->extension;
    }

    /**
     * @return mixed
     */
    public function getFileSize()
    {
        return $this->file_size;
    }

}

搜索功能實作 search.php

<?php

// 接收請求資料
$pageNo = $_GET['page'] ?? 1;
$pageSize = 9;

// 接收查詢引數
$keywords = $_GET['keywords'] ?? '';

$data = [];
//模擬加載中的圖示sleep(3);
try {
    $pdo = new PDO('mysql:host=localhost:3306;dbname=pic',
        'root',
        '123456',
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    // 請求mysql 查詢記錄總數
    $sql = 'SELECT count(*) AS aggregate FROM pic';
    if (strlen($keywords) > 0) {
        $sql .= ' WHERE info like ?';
    }
    $stmt = $pdo->prepare($sql);
    if (strlen($keywords) > 0) {
        $stmt->bindValue(1, '%' . $keywords . '%', PDO::PARAM_STR);
    }
    $stmt->execute();
    $total = $stmt->fetch(PDO::FETCH_ASSOC)['aggregate'];
    
    // 計算最大頁碼,設定頁碼邊界
    $minPage = 1;
    $maxPage = ceil($total / $pageSize); // 3.6
    $pageNo = max($pageNo, $minPage);
    $pageNo = min($pageNo, $maxPage);
    $offset = ($pageNo - 1) * $pageSize;


    $sql="SELECT `path`,`info` FROM pic ";
    if (strlen($keywords) > 0) {
        $sql .= ' WHERE info like ?';
    }
    $sql .= 'ORDER BY id DESC LIMIT ?, ?';
    $stmt = $pdo->prepare($sql);
    if (strlen($keywords) > 0) {
        $stmt->bindValue(1, '%' . $keywords . '%', PDO::PARAM_STR);
        $stmt->bindValue(2, (int)$offset, PDO::PARAM_INT);
        $stmt->bindValue(3, (int)$pageSize, PDO::PARAM_INT);
    } else {
        $stmt->bindValue(1, (int)$offset, PDO::PARAM_INT);
        $stmt->bindValue(2, (int)$pageSize, PDO::PARAM_INT);
    }
    $stmt->execute();
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $data = [
        'code' => 1,
        'msg' => 'ok',
        'rows' => $results,
        'total_records' => (int)$total,
        'page_number' => (int)$pageNo,
        'page_size' => (int)$pageSize,
        'page_total' => (int)$maxPage,
    ];   

} catch (PDOException $e) {
    $data = [
        'code' => 0,
        'msg' => $e->getMessage(),
        'rows' => [],
        'total_records' => 0,
        'page_number' => 0,
        'page_size' => (int)$pageSize,
        'page_total' => 0,
    ];
}

header('Content-type: application/json');
echo json_encode($data);

最后資料庫格式 

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 80012
Source Host           : localhost:3306
Source Database       : pic

Target Server Type    : MYSQL
Target Server Version : 80012
File Encoding         : 65001

Date: 2020-01-14 16:22:49
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for pic
-- ----------------------------
DROP TABLE IF EXISTS `pic`;
CREATE TABLE `pic` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `path` varchar(255) DEFAULT NULL,
  `mark` tinyint(3) DEFAULT NULL,
  `scale` varchar(255) DEFAULT NULL,
  `info` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of pic
-- ----------------------------
INSERT INTO `pic` VALUES ('1', './uploads/5e1d788084cc5.jpg', '1', '800*600', '這是測驗圖片1');
INSERT INTO `pic` VALUES ('2', './uploads/5e1d789766591.jpg', '1', '600*450', '這是測驗圖片2');

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/84971.html

標籤:PHP

上一篇:GD庫的基本資訊,影像的旋轉、水印、縮略圖、驗證碼,以及影像類的封裝

下一篇:檔案管理系統

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more