一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

PHP实现文件上传和下载代码展示

时间:2022-10-13 编辑:坚强 来源:一聚教程网

本文为小伙伴们带来了关于PHP实现文件上传和下载代码展示,感兴趣的小伙伴不要错过了,一起来看看吧。

1.效果图

2.首先是封装好的图片类(缩放及生成水印)

1.GDBasic.php

='))
        {
            throw new Exception("GD requires GD version '2.0.1' or greater, you have " . $version);
        }
 
        self::$_check = true;
        return self::$_check;
    }
}

2.Image.php

createImageByFile($file);
        $this->_width'];
        $this->_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样式不是重点,先不放了

3.ajax类封装文件

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

1.index.php



 

    
    
    css/bootstrap.min.css" rel="external nofollow"  rel="stylesheet">
    
    
    

 

    
    
    
    
    

文件上传下载

实现文件的上传和下载功能

2.图片相关功能处理

upload_class.php

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 testLibImage($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("");
}
catch(PDOException $e)
{
    echo $sql . "
" . $e->getMessage(); }

3.封装好的文件上传类

UploadFile.php

 '文件大小超出了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;
    }
 
}

4.搜索功能实现

search.php

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

4.最后数据库格式 

/*
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',

以上就是关于PHP实现文件上传和下载代码展示的全部内容了,感兴趣的小伙伴记得点击关注哦。

热门栏目