使用Ajax上传用户头像
打赏作者

lenglvse

请问下 头像上传 成功了 但是放回 json 的 时候参数 不对
ErrorException in Arr.php line 145:
array_key_exists(): The first argument should be either a string or an integer

lenglvse

如果将 返回 的 ‘success’=> true 改为 ‘success’=> ‘true’ 没有报错 但是 长传成功后 头像 并没有更换 刷新 才可以

lenglvse

windows平台 开发的 换了 浏览器也不行

lenglvse

目前 解决 方案是 直接 return 了 让后 页面 window.location.reload(); 感觉 不太理想

yaoye6262

请问一下 我想使用ajax正常提交表单 应该怎么写ajax代码? 后台要怎么写? 能给个代码参考一下吗?

yaoye6262 回复 JellyBool

vue.js 也可以实现ajax局部刷新?? 学习vue js之前 需要先学习其他什么吗?

saloou

请问老师:我在执行到这里代码 就出错,后面的代码就执行了!老师帮我分析分析 是哪里的问题呢?感谢。

  $destinationPath = 'uploads/';
  $filename = \Auth::user()->id . '_' . time() . $file->getClientOriginalName();
        $file->move($destinationPath, $filename);

        Image::make($destinationPath, $filename)->fit(100)->save(); //执行到这后 出错 
        $user = User::find(\Auth::user()->id);
        $user->avatar = '/' . $destinationPath . $filename;
        $user->save();
JellyBool 回复 saloou

具体报错是什么?看看目录对不?有权限写入不?

saloou 回复 JellyBool

没有任何 提示,有读写权限,move()都成功了!

就是感觉没有image::make()方法是的!!make()方法下面有一道横线!

JellyBool 回复 saloou

你一行一行 debug 一下,Image::make 这个只要你配置和 alias 应该就是没错的。

saloou 回复 JellyBool

好的,我研究研究,感谢回复

saloou 回复 JellyBool

反复看了你的教程,终于搞定啦!感谢

那天与你邂逅的波哥

avatar:99 Uncaught TypeError: $(…).ajaxForm is not a function
at HTMLInputElement. (avatar:99)
at HTMLInputElement.dispatch (jquery.min.js:3)
at HTMLInputElement.q.handle (jquery.min.js:3)
浏览器报这个错误,怎么解决

JellyBool 回复 那天与你邂逅的波哥

注意引入 ajaxForm js 文件和它的顺序,放在 jquery 之后

那天与你邂逅的波哥 回复 JellyBool
<script src="/js/bootstrap.min.js"></script>
<script src="/js/jquery.form.js"></script>

就是放在之后啊

JellyBool 回复 那天与你邂逅的波哥

纳尼,还有其他的错误么?

那天与你邂逅的波哥 回复 JellyBool

没有其他错误
/js/jquery.form.js好像没起作用

那天与你邂逅的波哥 回复 JellyBool

点上传一直显示正在上传

JellyBool 回复 那天与你邂逅的波哥

你用的是这个么?

https://github.com/JellyBool/laravel-app/blob/master/jquery.form.js

把代码贴出来看看吧,用 markdown 排版一下

那天与你邂逅的波哥 回复 JellyBool

是这个啊
public function changeAvatar(Request $request)
{
file=file=request->file(‘avatar’);
$input = array(‘image’ => $file);
$rules = array(
‘image’ => ‘image’
);
validator=Validator::make(validator = Validator::make(input, $rules);
if ( $validator->fails() ) {
return \Response::json([
‘success’ => false,
‘errors’ => $validator->getMessageBag()->toArray()
]);

    }
    $destinationPath = 'uploads/';
    $filename=\Auth::user()->id.'_'.time().$file->getClientOriginalName();
    $file->move($destinationPath,$filename);
    \Image::make($destinationPath.$filename)->fit(200)->save();
    $user=User::find(\Auth::user()->id);
    $user->avatar='/'.$destinationPath.$filename;
    $user->save();

return \Response::json([
    'success'=>true,
    'avatar'=>asset($destinationPath.$filename),
]);
}这是控制器的
JellyBool 回复 那天与你邂逅的波哥

你的前端代码呢?还有chrome 的所有报错

那天与你邂逅的波哥 回复 JellyBool

@extends(‘app’)
@section(‘content’)

{!! Form::open(['url'=>'/avatar','files'=>true,'id'=>'avatar']) !!}
{!! Form::file('avatar',['class'=>'avatar','id'=>'image']) !!} {!! Form::close() !!}
@stop 浏览器报错 Uncaught TypeError: $(...).ajaxForm is not a function at HTMLInputElement. (avatar:100) at HTMLInputElement.dispatch (jquery-3.0.0.min.js:3) at HTMLInputElement.q.handle (jquery-3.0.0.min.js:3)
JellyBool 回复 那天与你邂逅的波哥
$(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('更换新的头像');
    }
}

这一堆代码是在 jquery 和 form.js 引入的后面吗?

你使用的是 jquery-3.0 版本?换过 2.4 版本么

那天与你邂逅的波哥 回复 JellyBool

引入是放在app模板的 版本换了好多个

JellyBool 回复 那天与你邂逅的波哥

用这个的 时候贴一下完整的代码可以么

https://github.com/JellyBool/laravel-app/blob/master/jquery-2.1.4.min.js

是怎么引入的,各个部分的代码是什么样的

那天与你邂逅的波哥 回复 JellyBool
laravel app
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="/js/jquery.form.js" ></script>
   <script src="//cdn.bootcss.com/tether/1.3.6/js/tether.min.js"></script>
   <script src="/js/bootstrap.min.js"></script>
@yield('content')
JellyBool 回复 那天与你邂逅的波哥

你引入了两个 jquery ?

那天与你邂逅的波哥 回复 JellyBool

最后那个是美化社区那个视频时候引入的啊

那天与你邂逅的波哥 回复 JellyBool

我把2个合并了,那个错误解决了
但还是不能传头像浏览器报Failed to load resource: the server responded with a status of 500 (Internal Server Error)

JellyBool 回复 那天与你邂逅的波哥

后端代码有问题吧。。。点开 chrome 的报错就可以看到具体的报错信息了啊

那天与你邂逅的波哥 回复 JellyBool

解决了,搞了大半天,谢谢啦

alexsunkang 回复 那天与你邂逅的波哥

您好朋友,我现在遇到跟您一样的问题 一直显示 “正在上传”

alexsunkang 回复 那天与你邂逅的波哥

请问您是怎么解决的呢?

那天与你邂逅的波哥 回复 alexsunkang

我引入了2个jquery,我把2个合并了就解决了,不知道你是什么问题

alexsunkang 回复 那天与你邂逅的波哥

我已经解决了 谢谢啊朋友

Ruanjun 回复 alexsunkang

请问你是怎么解决的

blaze0207 回复 那天与你邂逅的波哥

請問大大要怎麼合併?
我也出現了這個錯誤~~!!

Uncaught TypeError: $(...).ajaxForm is not a function

沒事兒~~已解決問題!!

Ruanjun 回复 那天与你邂逅的波哥

我也是卡在一直上传中,但是没有任何报错

nature327 回复 Ruanjun

我的也是Failed to load resource: the server responded with a status of 500 (Internal Server Error)这个错误,请问你怎么解决的?

nature327 回复 Ruanjun

解决了,导错一个包

hate 回复 那天与你邂逅的波哥

怎么可以那么丑

1833183060

视频中提到的 文章在哪里 ?我怎么打不开?

Ruanjun

我这边尝试用jquery提交数据,但是一直提示正在上传…中。。。。

$('#image').on('change', function () {
                $('#upload-avatar').html('正在上传...');
                $('#avatar').ajaxForm(options).submit();
            });

似乎没有走到ajaxForm里面

JellyBool 回复 Ruanjun

console 是什么报错?

Ruanjun 回复 JellyBool

控制台没有报错,我现在已经放弃这种方法了。

JellyBool 回复 Ruanjun

行,这种思路实现起来可以就OK

Ruanjun

html代码

<div class="text-center">
                            <div id="validation-errors"></div>

                            <img src="{url(Auth::user()->avatar)}" width="120" class="img-circle" id="user-avatar">

                            {!! Form::open(['route' => 'avatar','files'=>true,'id'=>'avatar']) !!}
                            <div class="text-center" style="margin-bottom: 30px">
                                <button type="button" class="btn btn-success avatar-button" id="upload-avatar">
                                    上传新的头像
                                </button>
                            </div>

                            <div class="form-group">
                                {!! Form::file('avatar', ['class' => 'form-control','id'=>'image','accept'=>'image/jpg, image/png']) !!}
                            </div>
                            {!! Form::close() !!}
                            <div class="span5">
                                <div id="output" style="display:none"></div>
                            </div>
                        </div>

js代码

$(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 {
                console.log(response)
                $('#user-avatar').attr('src', response.avatar);
                $('#upload-avatar').html('更换新的头像');
            }
        }
nature327

@那天与你邂逅的波哥,你好,我的也是Failed to load resource: the server responded with a status of 500 (Internal Server Error)这个错误,请问你怎么解决的?

q646448149

这个功能我实现了,可是我这边还是浏览器那样,选择文件的那个按钮上传。并不是那个上传新的头像按钮上传的。我不知道为什么按钮样式没有改变呢。还有,麻烦问下更换头像,特别感谢的那个logo引入的css在哪里呢?bootstrap下载的文件里面好像没有啊。谢谢

JellyBool 回复 q646448149

应该是关键词 font awesome,你找这个 icon 字体

yuhangbin

功能可以实现但是图片没有变化需要刷新是哪里出了问题?

JellyBool 回复 yuhangbin

你使用 js 更新一下图片的地址就好

carrywu

①如果出现POST http://localhost:8888/avatar 500 (Internal Server Error)类似这样的问题 首先返回控制台查找错误信息,一般是后台代码出错,比如Class Image之类没有引入,这个时候就返回上一个视频去仔细核对,注意一定要引入Intervention\Image\Facades\Image;然后Image::make(destinationPath.destinationPath.filename)->fit(200)->save();
②JS文件不需要引入两个,比如前几个视频中讲到社区样式的可以和这期视频的JS文件合并,大概只需要引入2.1.4和bootstrap和form.js这三个文件
坑挺多的,毕竟Laravel已经不是前几年的版本了,需要自己多注意

Flourishing

需要用到的代码片段直接去Jelly github地址获取就行 js文件也是 还有这里一定要写对 应该都不会出问题的:

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