如何使用带有基本URL的Laravel在数据库中存储图像

时间:2018-12-31 10:33:12

标签: php laravel-5.7 intervention

当我将图像存储到数据库中时,它不会使用基本URL上传。如何在Laravel中解决此类问题?

public function uploadimage(Request $request)
{
    if ($request->hasFile('image')) {
        $file = $request->file('image');
        $filename = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $picture = date('His') . '-' . $filename;
        $file->move(public_path('img'), $picture);

        $employee_image = Image::create($request->all());
        $employee_image->image = $filename;
        $employee_image->save();

        return response()->json(['message' => 'Image Uploaded Successfully']);
    }

    return response()->json(['message' => 'Select image first.']);
}

2 个答案:

答案 0 :(得分:1)

public_path()函数无意用于提供对浏览器友好的uri,因此,您应该改用\Illuminate\Support\Facades\URL门面。

例如:

$employee_image->image = URL::asset('storage/employees/').$filename;
$employee_image->save();

Source: Laravel.IO

答案 1 :(得分:0)

尝试一下...。

 public function uploadimage(Request $request)
{
    $this->validate($request, [
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);
    $employees = new Image($request->input()) ;

     if($file = $request->hasFile('image')) {
        $file = $request->file('image') ;
        $fileName = $file->getClientOriginalName() ;
        $destinationPath = public_path().'/images/' ;
        $file->move($destinationPath,$fileName);
        $employees->image = '/public/images/'.$fileName ;
    }
    $employees->save() ;
   return response()->json(['message' => 'Image Uploaded Successfully']);
}