首页 > 代码库 > Laravel5.1 搭建简单的社区(十二)--Ajax更换头像

Laravel5.1 搭建简单的社区(十二)--Ajax更换头像

此篇记录如何使用ajax进行头像的更换,使用ajax需要引入一个jQuery的插件 jQuery form,在app.blade.php中引入:

    <link rel="stylesheet" href="/css/bootstrap.css">
    {{--引入fontawesome--}}
    <link rel="stylesheet" href="/css/font-awesome.css">
    <link rel="stylesheet" href="/css/style.css">
    {{--引入jQueryform插件--}}
    <script src="/js/jquery-2.1.4.min.js"></script>
    <script src="/js/bootstrap.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery.form/4.2.1/jquery.form.js"></script>

引入插件后对avatar.blade.php的前端页面进行修改:

<div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <div class="text-center">
                    <div id="validation-errors"></div>
                    <img src="{{Auth::user()->avatar}}" width="120" class="img-circle" id="user-avatar" alt="">
                    {!! Form::open([‘method‘ => ‘post‘, ‘url‘=>‘user/avatar‘,‘id‘=>‘avatar‘,‘files‘=>true]) !!}
                    <div class="text-center">
                        <button type="button" class="btn btn-success avatar-button" id="upload-avatar">上传新的头像</button>
                    </div>
                    {!! Form::file(‘avatar‘,[‘class‘=>‘avatar‘,‘id‘=>‘image‘]) !!}
                    <!-- 提交 -->
                    {!! Form::close() !!}
                    <div class="span5">
                        <div id="output" style="display:none">
                        </div>
                    </div>
                    {{--{!! Form::open([‘method‘=>‘post‘,‘url‘=>‘user/avatar‘,‘files‘=>true]) !!}--}}
                    {{--Avatar 上传--}}
                    {{--{!! Form::file(‘avatar‘) !!}--}}
                    {{--<!-- 提交 -->--}}
                    {{--{!! Form::submit(‘tijao‘,[‘class‘ => ‘btn btn-primary form-control‘]) !!}--}}
                    {{--{!! Form::close() !!}--}}
                </div>
            </div>
            @if($errors->any())
                <ul class="list-group">
                    @foreach($errors->all() as $error)
                        <li class="list-group-item list-group-item-danger">{{ $error }}</li>
                    @endforeach
                </ul>
            @endif
        </div>
    </div>

然后写js代码:

<script>
        $(document).ready(function() {
            var options = {
                beforeSubmit:  showRequest,
                success:       showResponse,
                dataType: json
            };
            $(#image).on(change, function(){
                $(#upload-avatar).html(正在上传...);
                $(#avatar).ajaxForm(options).submit();
            });
        });
        function showRequest() {
            $("#validation-errors").hide().empty();
            $("#output").css(display,none);
            return true;
        }

        function showResponse(response)  {
            if(response.success == false)
            {
                var responseErrors = response.errors;
                $.each(responseErrors, function(index, value)
                {
                    if (value.length != 0)
                    {
                        $("#validation-errors").append(<div class="alert alert-error"><strong>+ value +</strong><div>);
                    }
                });
                $("#validation-errors").show();
            } else {
                $(#user-avatar).attr(src,response.avatar);
                $(#upload-avatar).html(更换新的头像);
            }
        }
    </script>

前端的工作到此为止,我们来处理后台的业务逻辑:

    public function changeAvatar(Request $request)
    {
        // 声明路径名
        $destinationPath = ‘uploads/‘;
        // 取到图片
        $file = $request->file(‘avatar‘);

        $input = array(‘image‘ => $file);
        $rules = array(
            ‘image‘ => ‘image‘
        );
        $validator = \Validator::make($input, $rules);
        if ( $validator->fails() ) {
            return \Response::json([
                ‘success‘ => false,
                ‘errors‘ => $validator->getMessageBag()->toArray()
            ]);
        }

        // 获得图片的名称 为了保证不重复 我们加上userid和time
        $file_name = \Auth::user()->id . ‘_‘ . time() . $file->getClientOriginalName();
        // 执行move方法
        $file->move($destinationPath, $file_name);

        // 裁剪图片 生成200x200的缩略图
        Image::make($destinationPath . $file_name)->fit(200)->save();
        // 保存到User
        $user = User::findOrFail(\Auth::user()->id);
        $user->avatar = ‘/‘ . $destinationPath . $file_name;
        $user->save();

        return \Response::json([
            ‘success‘ => true,
            ‘avatar‘ => asset($destinationPath.$file_name),
        ]);
    }

注意这里返回的是json文件

Laravel5.1 搭建简单的社区(十二)--Ajax更换头像