TP5整合阿里雲OSS上傳文件第二節,異步上傳頭像(下)

是這個功能的最後一步了,
新增插件:
layer.js 彈窗層組件
jquery.form 異步表單提交插件php

新增CSS:
layer擴展文件 修改layer彈窗的皮膚,默認的不喜歡!
基本代碼和以前第二節的差很少,修改了upload.js裏面的一點點東西css

先看看演示吧!
5aff13e891126.gif
簡單的數據表: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;
    }
}
相關文章
相關標籤/搜索