是这个功能的最后一步了,
新增插件:
layer.js 弹窗层组件
jquery.form 异步表单提交插件php
新增CSS:
layer扩展文件 修改layer弹窗的皮肤,默认的不喜欢!
基本代码和以前第二节的差很少,修改了upload.js里面的一点点东西css
先看看演示吧!
简单的数据表:html
-- 图片表 DROP TABLE IF EXISTS images; CREATE TABLE IF NOT EXISTS images( id INT(11) UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT 'id', img_url VARCHAR(255) NOT NULL DEFAULT '' COMMENT '图片名称', create_time INT NOT NULL DEFAULT 0 COMMENT '建立时间', update_time INT NOT NULL DEFAULT 0 COMMENT '更新时间' )ENGINE innodb CHARSET utf8 COMMENT '图片表'; -- 用户表 DROP TABLE if EXISTS user; CREATE TABLE IF NOT EXISTS user( id INT(11) UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT 'id', img_id int(11) UNSIGNED NOT NULL DEFAULT 0 COMMENT '图片ID', create_time INT NOT NULL DEFAULT 0 COMMENT '建立时间', update_time INT NOT NULL DEFAULT 0 COMMENT '更新时间' )ENGINE innodb CHARSET utf8 COMMENT '用户表';
以后再aliyunOss配置文件中增长一个配置,就是访问的域名;jquery
//阿里云OSS配置 return [ 'KeyId' => '***', //您的Access Key ID 'KeySecret' => '***', //您的Access Key Secret 'Endpoint' => '****', //阿里云oss 外网地址endpoint 'Bucket' => '****', //Bucket名称 'OssDomain' => 'http://thinkpjax.cn/', // 这个配置是新增的 ];
建立基础模型类 (application/index/model/base.php)web
<?php /** * User: 李昊天 * Date: 2018/5/19 * Time: 0:50 * Email: haotian0607@gmail.com */ namespace app\index\model; use think\Model; class Base extends Model { public function img() { return $this->hasOne('Images','id','img_id'); } }
建立用户模型(application/index/model/User.php) 继承基础模型类
建立图片模型(application/index/model/Images.php)ajax
<?php /** * User: 李昊天 * Date: 2018/5/19 * Time: 0:54 * Email: haotian0607@gmail.com */ namespace app\index\model; use think\facade\Config; use think\Model; class Images extends Model { /** * 设置读取器 * 在读取图片地址的时候将配置文件中的OssDomain.数据库里面的图片地址 * @param $url * @return string */ public function getImgUrlAttr($url) { return Config::get('aliyunOss.OssDomain').$url; } }
修改upload.js数据库
$ImgId = $face.find($("input[name='imgId']")); if (!$ImgId.length) { $ImgId = $face.append('<input name="imgId" type="hidden">'); }
$face.find($("input[name='imgId']")).val(response.data.imgId);后端
完整代码:浏览器
/** * User: 李昊天 * Date: 2018/5/18 * Time: 1:15 * Email: haotian0607@gmail.com */ $(function () { var $face = $("#face"), thumbnailWidth = 100, thumbnailHeight = 100; //建立uploader实例 WebUploader.create({ server: uploaderUrl, //服务器异步接受地址! pick: { id: "#changeFile", //指定选择文件的按钮容器 multiple: false, //禁止多选 }, resize: false, //不压缩image auto: true, //选择以后自动上传 swf: '../flash/Uploader.swf', //防止低版本浏览器 用到了flash // 只容许选择图片文件。 accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } }).on('fileQueued', function (file) { // 当有文件添加进来的时候 var $img = $face.find('img'); //获取到头像的DOM // 建立缩略图 this.makeThumb(file, function (error, src) { if (error) { $img.replaceWith('<span>不能预览</span>'); return; } $img.attr('src', src); }, thumbnailWidth, thumbnailHeight); }).on('uploadProgress', function (file, percentage) { // 文件上传过程当中建立进度条实时显示。 $percent = $face.find(".progress .progress-bar"); $ImgId = $face.find($("input[name='imgId']")); if (!$ImgId.length) { $ImgId = $face.append('<input name="imgId" type="hidden">'); } // 避免重复建立 if (!$percent.length) { //构建进度条DOM $face.append('<div class="dialog"></div>'); //这个是提示框 $percent = $('<div class="progress"><div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 10%;"><span></span></div></div>').appendTo($face).find('progress-bar'); } $percent.css({'width': 50 + '%'}); //让进度条动起来 }).on('uploadSuccess', function (file, response) { // 文件上传成功,给dialog添加class, 用样式标记上传成功。 //找到头像DIV下面的dialog 添加一个success的样式类将内容改变成上传成功而且显示! $face.find('.dialog').addClass('success').text('上传成功').show(); $face.find($("input[name='imgId']")).val(response.data.imgId); }).on('uploadError', function (file) { // 文件上传失败,一样是添加Class //找到头像DIV下面的dialog 添加一个error的样式类将内容改变成上传失败而且显示! $face.find('.dialog').addClass('error').text('上传失败').show(); }).on('uploadComplete', function (file) { // 完成上传完了,成功或者失败,先删除进度条。 $face.find('.progress').remove(); }); });
修改up.html里面的代码:
主要是加入表单,加入提交按钮,加入form.js和layer.js
主要部分代码:服务器
<form action="{{:url('index/User/modify')}}" id="modifyForm" method="post"> <div id="face"> <img src="{{$data.img.img_url|default='/static/img/default.png'}}" alt="" class="img-thumbnail"> </div> <div id="changeFile">选择文件</div> <div style="position:relative;top:250px;text-align:center;"> <button type="button" id="submitBtn" class="btn" style="margin-left: -70px;">提交修改</button> </div> </form>
加入操做的js
<script> $(function () { layer.config({ extend: 'web/style.css', skin: 'web' }); $("#submitBtn").on('click', function () { var $input = $("input[name='imgId']"); if ($input.length < 1 || $input.val() == '') { layer.tips('请先上传图片', $("#changeFile"), { tips: [2, '#E4393c'], time: 4000 }); return; } $("#modifyForm").ajaxSubmit({ beforeSend: function () { layer.load(); }, success: function (res) { var ico = 1; if (res.status == 1) ico = 1; else ico = 2; layer.alert(res.msg, {icon: ico, shade: 0.2}); }, complete: function () { layer.closeAll('loading'); }, error: function (jqXHR, textStatus, errorThrown) { switch (jqXHR.status) { case(500): layer.alert('服务器系统内部错误!' + textStatus, {icon: 2}); break; case(408): layer.alert('请求超时!' + textStatus, {icon: 3}); break; default: layer.alert('请求出错!' + textStatus, {icon: 2}); } }, }) }); }); </script>
后端代码也有更改:
public function uploadFile() { // sleep(3); $file = request()->file('file'); //获取到上传的文件 $resResult = Image::open($file); try { $config = Config::pull('aliyun_oss'); //获取Oss的配置 //实例化对象 将配置传入 $ossClient = new OssClient($config['KeyId'], $config['KeySecret'], $config['Endpoint']); //这里是有sha1加密 生成文件名 以后链接上后缀 $fileName = sha1(date('YmdHis', time()) . uniqid()) . '.' . $resResult->type(); //执行阿里云上传 $result = $ossClient->uploadFile($config['Bucket'], $fileName, $file->getInfo()['tmp_name']); if ($result && $result['info']['http_code'] == 200) { try { $Images = new Images(); //实例化图片模型 $Images->allowField('img_url')->save([ 'img_url' => $fileName //写入上传的文件名 ]); return ajaxReturn(parent::SUCCESS, 'success', [ 'imgId' => $Images->id, ]); } catch (Exception $e) { return ajaxReturn(parent::FAIL, 'error'); } } else { return ajaxReturn(parent::FAIL, 'error'); } } catch (OssException $e) { return $e->getMessage(); } }
最好是在修改的时候判断表单传递的imgId与数据库里面的ID,若是一致就不容许修改!
修改逻辑代码:
public function modify() { if (request()->isPost()) { $userData = (new UserModel())->find(parent::$uid); if (null === $userData) { return ajaxReturn(parent::FAIL, '获取用户信息失败,请从新登陆!'); } $imgId = input('post.imgId', ''); $result = $userData->allowField('img_id')->save(['img_id' => $imgId]); if ($result) { return ajaxReturn(parent::SUCCESS, '修改为功!'); } else { return ajaxReturn(parent::FAIL, '操做失败!'); } } }
up控制器:
public function up() { /** * 使用动态关联预载入 */ $userData = (new UserModel())->with('img')->find(parent::$uid); return $this->fetch('up', [ 'data' => $userData, ]); }
基础模型类:
<?php /** * User: 李昊天 * Date: 2018/5/19 * Time: 0:44 * Email: haotian0607@gmail.com */ namespace app\index\controller; use think\Controller; class Base extends Controller { protected static $uid = ''; const SUCCESS = 1; const FAIL = 0; public function initialize() { //因为没有登陆使用了假数据 self::$uid = 1; } }