【问题标题】:Laravel Image Upload using ajax 500 Internal Server ErrorLaravel 图片上传使用 ajax 500 内部服务器错误
【发布时间】:2017-08-26 14:37:13
【问题描述】:

我正在尝试在 laravel 5.2 中使用 ajax 上传图像。但我仍然收到错误 500 Internal Server Error in route。 当我尝试使用 ajax 请求上传图像时,浏览器显示了正确的路由路径,但我仍然不明白为什么它仍然向我显示错误。

HTML

<!-- CHANGE AVATAR TAB -->
                        <div class="tab-pane" id="tab_1_2">

                            <div class="uploadimagediv"></div> 
                                {{ Form::open(array('url' => 'admin/avatar','method'=>'post','files'=>'true','id'=>'updateprofileimage'))  }}

                                <div class="form-group">
                                    <div class="fileinput fileinput-new" data-provides="fileinput">
                                        <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
                                            <img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&amp;text=no+image" alt=""/>
                                        </div>
                                        <div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;">
                                        </div>
                                        <div>
                                            <span class="btn default btn-file">
                                            <span class="fileinput-new">
                                            Select image </span>
                                            <span class="fileinput-exists">
                                            Change </span>
                                            <p class="text-danger" id="error_image"></p>
                                            <input type="file" id="picture" name="picture"/>
                                            {{--{{ Form::file('picture') }}--}}
                                            </span>
                                            <span class="error alert-danger">{{ $errors->first('picture') }}</span>
                                            <a href="javascript:;" class="btn default fileinput-exists" data-dismiss="fileinput">
                                            Remove </a>
                                        </div>
                                    </div>
                                    <div class="clearfix margin-top-10">

                                    </div>
                                </div>
                                <div class="margin-top-10">
                                    {{Form::hidden('id', 2, ["id"=>"id"])}}
                                    {{ Form::button('Upload',['id'=> 'updatepicture','class'=>'btn green-haze']) }}

                                    {{--{{ Form::submit('Submit',['class' => 'btn green-haze','name'=>'changeImage']) }}--}}
                                    <a href="javascript:;" class="btn default">
                                    Cancel </a>
                                </div>
                            {{ Form::close() }}
                        </div>
                        <!-- END CHANGE AVATAR TAB -->

路线

Route::group(['prefix' => 'admin'], function ()
{
    Route::controller('/','DashboardController');
});

Ajax

$(document).on('click', '#updatepicture', function($e)
{
    $e.preventDefault();
    // send an ajax request
    $("#error_image").empty();
    $.ajax(
    {

        url: 'avatar',
        processData: false,
        contentType: false,
        type: "post",//use for update
        data: new FormData($("#updateprofileimage")[0]),
        success: function(data)
        {
            if(data.status)
            {           
                $("#uploadimagediv").html('<div class="alert alert-success"><button type="button" class="close">×</button>'+data.message+'</div>');
                window.setTimeout(function()
                {
                    $(".alert").fadeTo(500, 0).slideUp(500, function()
                    {
                        $(this).remove(); 
                    });
                }, 5000);
                $('.alert .close').on("click", function(e)
                {
                    $(this).parent().fadeTo(500, 0).slideUp(500);
                });
                //console.log(data);
                //$("#updateprofileimage")[0].reset();
                //window.location.href = "http://localhost/laravel/admin/profile";
            }
            else
            {
                errors = data.errors;

                for(error in errors)
                {
                    $("#error_"+error.title).html(error.message);
                }
            }
        },
        error: function(xhr)
        {
            if(xhr.status == 422)
            {
                errors = xhr.responseJSON;
                for(error in errors)
                {
                    $("#error_"+error).html(errors[error][0]);
                }
            }
        }
    });
});

错误是:“NetworkError: 500 Internal Server Error - http://localhost/laravel/admin/avatar

请告诉我哪里出错了。

控制器是

public function postAvatar(ImageUploadRequest $request)
{
  ---
}

【问题讨论】:

    标签: ajax image laravel file-upload


    【解决方案1】:
    Add the below line inside <head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    And add the below lines before your ajax call in javascript function
    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
    });
    
    And don't forget to give permission to your storage folder
    sudo chmod -R 777 storage
    

    【讨论】:

    • 我仍然收到错误“NetworkError: 500 Internal Server Error - localhost/laravel/admin/avatar
    • 看起来你没有正确地将你的路由放在 ajax url 中,靠近 $.ajax( { url: 'avatar', 它必须是 url: '{{route('name')}}'
    【解决方案2】:

    在您的 ajax 设置中,您必须在请求中提供 x-csrf-token。对于您的 ajax 请求,您的网址也存在问题:

     $(document).on('click', '#updatepicture', function($e)
        {
            $e.preventDefault();
            // send an ajax request
            $("#error_image").empty();
            $.ajax(
            {
    
                url: "{{url('avatar')}}",
                processData: false,
                contentType: false,
                type: "post",//use for update
                data: new FormData($("#updateprofileimage")[0]),
                headers: {
                'X-CSRF-TOKEN': "{{ csrf_token() }}"
                },
                success: function(data)
                {
                    if(data.status)
                    {           
                        $("#uploadimagediv").html('<div class="alert alert-success"><button type="button" class="close">×</button>'+data.message+'</div>');
                        window.setTimeout(function()
                        {
                            $(".alert").fadeTo(500, 0).slideUp(500, function()
                            {
                                $(this).remove(); 
                            });
                        }, 5000);
                        $('.alert .close').on("click", function(e)
                        {
                            $(this).parent().fadeTo(500, 0).slideUp(500);
                        });
                        //console.log(data);
                        //$("#updateprofileimage")[0].reset();
                        //window.location.href = "http://localhost/laravel/admin/profile";
                    }
                    else
                    {
                        errors = data.errors;
    
                        for(error in errors)
                        {
                            $("#error_"+error.title).html(error.message);
                        }
                    }
                },
                error: function(xhr)
                {
                    if(xhr.status == 422)
                    {
                        errors = xhr.responseJSON;
                        for(error in errors)
                        {
                            $("#error_"+error).html(errors[error][0]);
                        }
                    }
                }
            });
        });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-12
    • 2020-02-12
    • 2018-04-16
    • 2016-03-24
    • 1970-01-01
    • 2018-02-04
    • 2019-05-12
    • 2015-09-20
    相关资源
    最近更新 更多