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('更换新的头像');
}
}