如何在 Laravel 中上传没有发送按钮且在上传后自动刷新的表单中的图像?
How can I upload an image from a form without a send button and with auto refresh after upload in Laravel?
我尝试了所有在互联网上找到的变体,但没有结果..
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>
只需创建一个 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>
我尝试了所有在互联网上找到的变体,但没有结果..
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>
只需创建一个 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>