本书未发布

52. 上传头像

未匹配的标注

概述

在本节里,我们使用上节开发的上传图片功能完成修改用户头像功能。

需求分解

  • 当用户还没有上传头像时,编辑表单预览显示 『上传图片』 默认图片;
  • 在本节里我们暂不限制上传图片格式和尺寸;

数据模型

首先,我们需要在用户更新信息方法( updateProfile )的 allowField 里添加上用户头像字段。

application/common/model/User.php

.
.
.
public function updateProfile($data)
{
    .
    .
    .
    $is_save = $this->allowField(['name', 'introduction', 'avatar'])
                    ->save($data, ['id' => $this->id]);
    if(!$is_save){
        throw new \Exception('更新个人信息失败');
    }
    .
    .
    .
}
.
.
.

助手方法

如上一节所说,我们前面实现的上传图片功能使用 IFrame 标签引入到编辑表单,为了方便调用,我们把使用 IFrame 引入上图图片功能定义成一个助手方法。

application/index/common.php

<?php
.
.
.
// application/common.php
/**
 * 上传单张图片--返回的是Upload Image Path
 * @Author   zhanghong
 * @DateTime 2019-02-18
 * @param    string     $backcall 回调字段名
 * @param    integer    $width    图片高度
 * @param    integer    $height   图片宽度
 * @param    string     $image    当前图片路径
 * @param    string     $upload_type    上传文件类型
 */
function create_upload_image($backcall="image", $width=100, $height=100, $image="")
{
    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width='.$width.' height="'.$height.'"  src="'.url('[upload.create]').'?width='.$width.'&height='.$height.'&backcall='.$backcall.'&image='.$image.'"></iframe>
         <input type="hidden" name="'.$backcall.'" id="'.$backcall.'">';
}

视图模板

接下来,我们在用户编辑信息表单里添加上传头像功能:

application/index/view/user/edit.html

{extend name="layout/main" /}
{block name="content"}
.
.
.
<div class="form-group">
    <label for="name-field">用户名</label>
    <input class="form-control" type="text" name="name" id="name-field" value="{$user->name}" />
</div>
<div class="form-group mb-4">
    <label for="" class="avatar-label">用户头像</label>
    {:create_upload_image("avatar", 100, 100, $user->avatar)}
</div>
<div class="form-group">
    <label for="introduction-field">个人简介</label>
    <textarea name="introduction" id="introduction-field" class="form-control" rows="3">{$user->introduction|default=''}</textarea>
</div>
.
.
.

效果展示

提交代码

下面把代码纳入到版本管理:

$ git add -A
$ git commit '上传头像'

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~