效果图
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(); preg_match("/\\d+\\.\\d+(?:\\.\\d+)?/",$info["GD Version"],1)">$matches)) { $version = $matches[0]; } 当gd库版本小于2.0.1 version_compare($version,'2.0.1','>='Exception("GD requires GD version '2.0.1' or greater,you have " . $version); } self::$_check = ; return self::; } }
Image.PHP
<?* * Image.PHP * description 图像类 namespace test\Lib; require_once 'GDBasic.PHP'; class Image extendsprotected $_width; $_height$_im$_type$_mime$_real_path; function __construct($file) { 检查GD库 self::check(); $imageInfo = $this->createImageByFile(); $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 */ function createImageByFile(检查文件是否存在 file_exists(Exception('file is not exits'获取图像信息 $imageInfo = getimagesize($realPath = realpath(); if(!$imageInfoException('file is not image file'switch($imageInfo[2]) { case IMAGETYPE_GIF: $im = imagecreatefromgif(); break; case IMAGETYPE_JPEG: $im = imagecreatefromjpeg(case IMAGETYPE_PNG: $im = imagecreatefrompng(default: throw Exception('image file must be png,jpeg,gif'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 function resize($width,1)">$heightis_numeric($width) || !Exception('image width or height must be number'); } 根据传参的宽高获取最终图像的宽高 $srcW = $this->_width; $srcH = _height; if($width <= 0 || $height <= 0) { $desW = $srcW;缩略图高度 $desH = $srcH;缩略图宽度 } else { $srcP = $srcW / 宽高比 $desP = $width / ; $width > $srcW) { $height > $srcH) { ; ; } { $desW = round($desH * $srcP); } } { $desP > $width$desH = $desW / ); } ); } } } PHP版本小于5.5 version_compare(PHP_VERSION,'5.5.0','<'$desIm = imagecreatetruecolor($desW,1)">$desH); if(imagecopyresampled($desIm,1)">$this->_im,1)">$desH,1)">$srcW,1)">)) { imagedestroy(_im); $desIm; $this->_width = imagesx($this->_height = imagesy(_im); } } { $desIm = imagescale()) { _im); } } return $this; } * * 根据百分比生成缩略图 * @param int $percent 1-100 * @return Image * @throws \Exception function resizeByPercent($percentintval($percent) <= 0Exception('percent must be gt 0'); } $percent = $percent) > 100 ? 100 : ); $percent = $percent / 100; $this->_width * $this->_height * $this->resize(); } * * 图像旋转 * @param $degree * @return $this function rotate($degree) { $degree = 360 - $back = imagecolorallocatealpha($im = imagerotate($degree,1)">$back,1); imagesavealpha(); imagedestroy(_im); $im_im); * * 生成水印 * @param file $water 水印图片 * @param int $pct 透明度 * @return $this function waterMask($water ='',1)">$pct = 60 ) { 根据水印图像文件生成图像资源 $waterInfo = $water); imagecopymerge(); 销毁$this->_im $waterInfo['im'; } * * 图片输出 * @return bool show() { header('Content-Type:' . _mime); $this->_type == 1) { imagegif(_im); $this->_type == 2) { imagejpeg(null,80$this->_type == 3) { imagepng(; } } * * 保存图像文件 * @param $file * @param null $quality * @return bool * @throws \Exception function save($file,1)">$quality = null获取保存目的文件的扩展名 $ext = pathinfo( PATHINFO_EXTENSION); strtolower($ext$ext || !in_array($ext,1)">array('jpg','jpeg','gif','png'))) { Exception('image save file must be jpg,png,1)">$ext === 'gif'; } $ext === 'jpeg' || $ext === 'jpg'$quality > 0$quality < 1$quality = 1$quality > 100$quality = 100; } imagejpeg($quality); } { imagejpeg($ext === 'png'; } } }
style样式不是重点,先不放了
然后是ajax类封装的文件 ajax.js
let $ = new class { constructor() { this.xhr = XMLHttpRequest(); this.xhr.onreadystatechange = () => { if (this.xhr.readyState == 4 && this.xhr.status == 200) { process response text let response = this.xhr.responseText; this.type == "json") { response = JSON.parse(response); } .callback(response); } } } get(url,parameters,callback,type = "text" url = test.PHP?username=zhangsan&age=20 parameters = {"username": "zhangsan","age": 20} let data = .parseParameters(parameters); if (data.length > 0) { url += "?" + data; } this.type = type; this.callback = callback; this.xhr.open("GET",url,1)">.xhr.send(); } post(url,1)">) { let data = this.xhr.open("POST",1)">this.xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded".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); } };
<!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="style/css/bootstrap.min.css" rel="stylesheet"> <link href="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> </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="10240000" /> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</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="1">添加</option> <option value="0">不添加</option> </select> </p> <br/> <p> 图片宽度比例: <select name="scale"> <option value="800*600">800*600</option> <option value="600*450">600*450</option> <option value="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="class.test.com" target="_blank">class.test.com</a> | XX网</h4> </ul> </div> </footer> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="style/js/jquery.min.js"></script> <!-- Include all compiled plugins (below),or include individual files as needed --> <script src="style/js/bootstrap.min.js"></script> <script type="text/JavaScript"> function show(){ if(document.getElementById("image").value == ''){ alert('请选择图片'); } if(document.getElementById("info").value == ''){ 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="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 = 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 ; } // next let nextBtn = ''; if (res.page_total == res.page_number) { nextBtn = '<li class="page-link" href="javascript:requestPage(' + (res.page_number + 1) + ');">Next</a></li>'; } else { nextBtn = '<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>
<?PHP 接收传过来的数据 $description=$_POST['description'];描述 $mark=$_POST['mark'];水印 $scale=$_POST['scale'];比例 800*600 $path='';图片存储路径 //根据比例获取宽高 $width=substr($scale,3);800 $height=600 //上传图片并存储 require('UploadFile.PHP'); $upload = new UploadFile('test_pic'); $upload->setDestinationDir('./uploads'$upload->setAllowMime(['image/jpeg','image/gif','image/png']); $upload->setAllowExt(['gif','jpg',1)">$upload->setAllowSize(2*1024*1024); if ($upload->upload()) { $filename=$upload->getFileName()[0]; $dir=getDestinationDir(); $path=$dir.'/'.$filename;图片存储的实际路径 } { var_dump(getErrors()); } 根据比例调整图像 require_once './lib/Image.PHP'; $image = new \test\Lib\Image($path放大并保存 $image->resize($height)->save($info = 根据不同的图像type 来创建图像 $info[2]) { case 1:IMAGETYPE_GIF $image = imagecreatefromgif(case IMAGETYPE_JPEG: $image = imagecreatefromjpeg(case 3: $image = imagecreatefrompng(default: echo '图像格式不支持'; } 添加水印 $mark==1){ $logo=imagecreatefrompng('./uploads/logo.png'); 添加水印 imagecopy($image,1)">$logo,imagesx($logo),imagesy($logo)); header('Content-type:image/png'); imagejpeg(); } $dst_image=imagecreatetruecolor(拷贝源图像左上角起始 imagecopy( $dst_image,1)"> ); imagejpeg(); 存入数据库 $servername = "localhost"$username = "root"$password = "123456"$dbname = "pic"try { $conn = new PDO("MysqL:host=$servername;dbname=$dbname",1)">$username,1)">$password 设置 PDO 错误模式,用于抛出异常 $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO pic(`path`,`mark`,`scale`,`info`) VALUES ('$path','$mark',1)">$scale',1)">$description')"; 使用 exec() ,没有结果返回 $conn->exec($sqlexit("<script>alert(\"图片上传成功!\");window.location=\"index.PHP\";</script>"); } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); }
<?* * Created by PHPStorm. * User: JasonLee * Date: 2018/11/11 * Time: 22:01 */ UploadFile { * * const UPLOAD_ERROR = [ UPLOAD_ERR_INI_SIZE => '文件大小超出了PHP.ini当中的upload_max_filesize的值',1)"> UPLOAD_ERR_FORM_SIZE => '文件大小超出了MAX_FILE_SIZE的值',1)"> UPLOAD_ERR_PARTIAL => '文件只有部分被上传',1)"> UPLOAD_ERR_NO_FILE => '没有文件被上传',1)"> UPLOAD_ERR_NO_TMP_DIR => '找不到临时目录',1)"> UPLOAD_ERR_CANT_WRITE => '写入磁盘失败',1)"> UPLOAD_ERR_EXTENSION => '文件上传被扩展阻止',1)"> ]; * * @var $field_name* * @var string $destination_dir* * @var array $allow_mime$allow_ext$file_org_name$file_type$file_tmp_name$file_error$file_size$errors$extension$file_new_name* * @var float|int $allow_size* * UploadFile constructor. * @param $keyName * @param string $destinationDir * @param array $allowMime * @param array $allowExt * @param float|int $allowSize $keyName,1)">$destinationDir = './uploads',1)">$allowMime = ['image/jpeg','image/gif'],1)">$allowExt = ['gif','jpeg'],1)">$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 function setDestinationDir(* * @param $allowMime function setAllowMime(* * @param $allowExt function setAllowExt(* * @param $allowSize function setAllowSize(* * @return bool upload() { 判断是否为多文件上传 $files = []; is_array($_FILES[$this->field_name]['name'])) { foreach($this->field_name]['name'] as $k => $v) { $files[$k]['name'] = $k]['type'] = $this->field_name]['type'][$k]; $k]['tmp_name'] = $this->field_name]['tmp_name'][$k]['error'] = $this->field_name]['error'][$k]['size'] = $this->field_name]['size'][]; } } { $files[] = field_name]; } $files $key => ) { 接收$_FILES参数 $this->setFileInfo($key,1)">); 检查错误 $this->checkError($key 检查MIME类型 $this->checkMime( 检查扩展名 $this->checkExt( 检查文件大小 $this->checkSize( 生成新的文件名称 $this->generateNewName(count((array)$this->getError($key)) > 0continue; } 移动文件 $this->moveFile($this->errors) > 0* * @return array getErrors() { errors; } * * @param $key * @return mixed function getError($this->errors[]; } function setFileInfo( $_FILES name type temp_name error size $this->file_org_name[$key] = $file['name'$this->file_type[$file['type'$this->file_tmp_name[$file['tmp_name'$this->file_error[$file['error'$this->file_size[$file['size'* * @param $key * @param $error function setError($error$key][] = * * @param $key * @return bool function checkError($this->file_error > UPLOAD_ERR_OK) { 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(file_error]); ; } } function checkMime(if (!$key],1)">allow_mime)) { 文件类型' . $key] . '不被允许!'function checkExt($this->extension[$key] = PATHINFO_EXTENSION); allow_ext)) { 文件扩展名' . $key] . '不被允许!'function checkSize($key] > allow_size) { 文件大小' . $key] . '超出了限定大小' . allow_size); * * @param $key function generateNewName($this->file_new_name[uniqid() . '.' . function moveFile(destination_dir)) { mkdir($this->destination_dir,0777,1)">); } $newName = rtrim(]; is_uploaded_file($key]) && move_uploaded_file($newName)) { ; } 上传失败!'* * @return mixed getFileName() { file_new_name; } * * @return string getDestinationDir() { destination_dir; } getExtension() { extension; } getFileSize() { file_size; } }
<? 接收请求数据 $pageNo = $_GET['page'] ?? 1$pageSize = 9 接收查询参数 $keywords = $_GET['keywords'] ?? ''; $data = []; 模拟加载中的图标sleep(3); { $pdo = new PDO('MysqL:host=localhost:3306;dbname=pic','root','123456',1)"> [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] ); 请求MysqL 查询记录总数 $sql = 'SELECT count(*) AS aggregate FROM pic'strlen($keywords) > 0) { $sql .= ' WHERE info like ?'; } $stmt = $pdo->prepare($stmt->bindValue(1,'%' . $keywords . '%',1)">PARAM_STR); } $stmt->execute(); $total = $stmt->fetch(PDO::FETCH_ASSOC)['aggregate']; 计算最大页码,设置页码边界 $minPage = 1; $maxPage = ceil($total / $pageSize); 3.6 $pageNo = max($pageNo,1)">$minPage); min($maxPage$offset = ($pageNo - 1) * $pageSize; $sql="SELECT `path`,`info` FROM pic "$sql .= 'ORDER BY id DESC LIMIT ?,?'PARAM_STR); $stmt->bindValue(2,(int)$offset,1)">PARAM_INT); $stmt->bindValue(3,1)">$pageSize,1)">PARAM_INT); } { PARAM_INT); } $results = $stmt->fetchAll(PDO::FETCH_ASSOC); [ 'code' => 1,'msg' => 'ok','rows' => $results,'total_records' => (int)$total,'page_number' => (int)$maxPage,1)"> ]; } catch (PDOException ) { [ 'code' => 0,'msg' => $e->getMessage(),'rows' => [],'total_records' => 0,'page_number' => 0,'page_total' => 0,1)"> ]; } 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 tinyint(3) PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT3 DEFAULT CHARSET=utf8; Records of picINSERT INTO `pic` VALUES ('1',./uploads/5e1d788084cc5.jpg800*600这是测试图片1'2./uploads/5e1d789766591.jpg600*450这是测试图片2');