【问题标题】:How can I upload an image from a form without a send button and with auto refresh after upload in Laravel?在 Laravel 中上传后,如何从没有发送按钮和自动刷新的表单上传图像?
【发布时间】:2020-06-12 22:25:59
【问题描述】:

我尝试了我在互联网上找到的所有变体,但没有结果..

web.php 的路由:Route::post('profile', 'UserController@update_avatar');

profile.blade.php 的形式:

<form id="avatar-form" enctype="multipart/form-data" action="/profile" method="POST">
  <label>Update Profile Image</label>
  <input type="hidden" name="name" value="{{ $user->name }}">
  <input type="file" name="avatar" id="avatar">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

控制器:

public function update_avatar(Request $request){
        if($request->hasFile('avatar')){
            $avatar = $request->file('avatar');
            $user = Auth::user()->name;
            $filename = $user;
            Image::make($avatar)->resize(300, 300)->save( public_path('images/avatars/' . $filename . '.jpg' ) );

            $user = Auth::user();
            $user->avatar = $filename;
            $user->save();
        }

        return redirect('profile')->with('success', 'Your avatar was uploaded with success !');
    }

有问题的脚本..:

<script>
        $("#avatar").click(function(){
            $.ajax({
                type: "POST",
                data: $('#avatar-form').serialize(),
                url: "<?php echo url('/profile') ?>",
                success:function(data){
                    console.log(data);
                },

            });
        });
    </script>

【问题讨论】:

    标签: json ajax laravel forms submit


    【解决方案1】:

    只需创建一个change 事件:

    <script>
            $("#avatar").change(function(){
                $.ajax({
                    type: "POST",
                    data: $('#avatar-form').serialize(),
                    url: "<?php echo url('/profile') ?>",
                    success:function(data){
                        window.location.href = window.location.href;
                    },
    
                });
            });
        </script>
    

    【讨论】:

    • 不是他想要的。但是脚本中的“url”可以吗?
    • @IliseiCristian 什么是 echo url('/profile') 给你的?
    • 我真的不知道,我是根据网上教程做的脚本
    • 把它作为第一个操作放入脚本中:alert("") 让我知道你看到了什么
    • 嗯,我上传图片的时候什么都没有,只出现上传图片的名字等等
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 2019-09-24
    • 2011-04-13
    • 2013-04-19
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多