我是 Laravel 的初学者,我找到了这段代码(我不知道 ajax/jquery)。当我尝试将图像上传到我的数据库时,出现此错误。我该如何解决?我可以用这个代码同时上传标题和图片吗?
错误是: 在 null 上调用成员函数 getClientOriginalExtension()
我的控制器是:
public function imagePost(request $request){
$request->validate([
'title' => ['string', 'max:128'],
'first_photo' => 'required|image|mimes:jpeg,png,jpg,svg|max:4096',
]);
if ($files = $request->file('first_photo')) {
$fileName = "first_photo-".time().'.'.$request->image->getClientOriginalExtension();
$request->image->public_path('/images/posts/posts_first_images/', $fileName);
$image = new Image;
$image->image = $fileName;
$image->save();
return Response()->json([
"first_photo" => $fileName
], Response::HTTP_OK);
}
title = $request->title;
$first_photo = $request->first_photo;
$save = Post::create([
'title' => $title,
'first_image' => $first_photo,
]);
if($save){
return back()->with('success','success');
}else{
return back()->with('error','error');
}
我的刀片是:
<form class="form-horizontal" method="POST" action="{{route('imagePost')}}" enctype="multipart/form-data" id="upload_image_form" >
@csrf
<div class="row">
<div class="col-md-12 mb-2">
<img id="image_preview_container"
alt="preview image" style="max-height: 150px;">
</div>
<div class="col-md-12">
<div class="form-group">
<input type="file" name="first_photo" placeholder="Choose image" >
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-12">
<input class="form-control" maxlength="128" name='title' placeholder="Title" required="" autofocus="">
</div>
</div>
</form>
还有我的 ajax/jquery(或者 javascript,我真的不知道我真的是菜鸟)
<script>
$(document).ready(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#first_photo').change(function(){
let reader = new FileReader();
reader.onload = (e) => {
$('#image_preview_container').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
});
$('#upload_image_form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: "{{ route('imagePost')}}",
data: formData,
cache:false,
contentType: false,
processData: false,
success: (data) => {
this.reset();
alert('Image has been uploaded successfully');
},
error: function(data){
console.log(data);
}
});
});
});
</script>
答案 0 :(得分:0)
改变
$request->image->getClientOriginalExtension();
到
$request->file('first_photo')->getClientOriginalExtension();
注意你的刀片你将它命名为“first_photo”
<input type="file" name="first_photo" placeholder="Choose image" >
所以总是检查输入名称和文件参数,名称必须相同。
// Move the image to public folder inside images folder:
$request()->file('first_photo')->move(public_path('images/posts/posts_first_images/'), $filename);