我想将图像上传到 laravel 中的公用文件夹和数据库中,但是我遇到了一些问题,Image is uploading into public folder but image is not saving into database.
有人可以帮我说一下哪里出了问题吗?这是我的代码。
控制器
public function clientaction(Request $request)
{
$validation = validator::make($request->all(),[
'select_file' =>'required|image|mimes:jpeg,png,jpg,gif|max:2048'
]);
if($validation->passes())
{
$image = $request->file('select_file');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
return response()->json([
'message' => 'Image Upload Successfully',
'class_name' => 'alert-success'
]);
}
else
{
return response()->json([
'message' => $validation->errors()->all(),
'class_name' => 'alert-danger'
]);
}
DB::table('logo-clients')->insert([
'select_file'=> $new_name
]);
}
路线
Route::get('DashBoard','AdminController@DashBoard');
Route::get('Clients','AdminController@clients');
Route::post('/ajax_upload/action','AdminController@clientaction')->name('ajaxupload.action');
答案 0 :(得分:2)
因为您已经在返回值,这意味着之后的操作没有用
所以您只需要移动
DB::table('logo-clients')->insert([
'select_file'=> $new_name
]);
在这部分下面
$image->move(public_path('images'), $new_name);
//move it into here
答案 1 :(得分:1)
因为您已通过验证return
。请查看您通过验证并失败后返回两次的代码。我建议您在通过验证后返回response()->json()
之前先将代码保存到数据库中,然后移动代码。
答案 2 :(得分:1)
将文件移入文件夹后,您的函数将返回。因此不会执行数据库插入代码。您的功能应该像
public function clientaction(Request $request) {
$validation = validator::make($request->all(),[
'select_file' =>'required|image|mimes:jpeg,png,jpg,gif|max:2048'
]);
if($validation->passes())
{
$image = $request->file('select_file');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
}
else
{
return response()->json([
'message' => $validation->errors()->all(),
'class_name' => 'alert-danger'
]);
}
DB::table('logo-clients')->insert([
'select_file'=> $new_name ]);
return response()->json([
'message' => 'Image Upload Successfully',
'class_name' => 'alert-success'
]);
}