如何使用laravel控制器使用axios更新图像?

时间:2019-07-06 17:27:18

标签: laravel axios

我尝试通过不重新加载页面来更新图像。因此,我使用axios并很难使它工作。

这是我的表单

    <form id="avatar-upload" action="{{route('profile.update',['id'=>Auth::id()])}}" name="avatar-upload" method="POST" enctype="multipart/form-data">
                            {{method_field('PUT')}}
                                    @csrf

                                    <div class="avatar-wrapper">
                                            <img class="profile-pic" src="{{asset('storage/'. Auth::user()->avatar)}}" />
                                            <div class="upload-button">
                                                <i class="fa fa-arrow-circle-up" aria-hidden="true" ></i>


                                            </div>
                                            <input id="avatar" name="avatar" class="file-upload" type="file"  accept="image/*"/>
                                            <input id="authenticated_user_id" type="hidden" value="{{Auth::id()}}"> 
                                        </div>

                                        {{-- <p>{{Auth::id()}}</p> --}}

                                </form>

这是我的axios代码:

    $('#avatar-upload').submit(function (e) {

            e.preventDefault();

            var authenticated_user_id = $('#authenticated_user_id').val();

            console.log(authenticated_user_id);

                var form_data = new FormData(this);

                axios.put('http://localhost:8000/profile/' + authenticated_user_id, {
                    avatar: form_data,
                                        }).then((response) => { 

                                                    console.log( response.config);

                                                }).catch((error) => {
                                                     console.log(error);
                            });

                    });

这是我的更新方法:

    public function update(Request $request, $id)
        {

           if($request->hasFile('avatar')){
            $logged_in_user = Auth::user();
            $avatar = $request->file('avatar');
            $filename = Str::random().'.'.$avatar->getClientOriginalExtension();

            Image::make($avatar)->resize(300,300)->save(public_path('storage/users/'.date('F').date('Y').'/'.$filename));



            $image_with_storage_path = 'users/'.date('F').date('Y').'/'.$filename;




            $logged_in_user->avatar =  $image_with_storage_path;



              $logged_in_user->update(['avatar'=> $image_with_storage_path]);





           }

    return response('success');

    }

预期结果:“成功”以及数据库中的图像更新

  

实际结果:{url:“ http://localhost:8000/profile/1”,方法:“ put”,数据:“ {” avatar“:{}}”,标头:{…},transformRequest:Array(1),… }

如果更新功能完全在运行,我会感到困惑吗?

0 个答案:

没有答案