Home > database >  Why doesn't my php laravel application store my image?
Why doesn't my php laravel application store my image?

Time:04-25

I've looked at code from other people and try to implement the same thing, but the application could not store the image to the desire folder, would you please have a look at what the reason is? Thank you! Here is my code for route:

Route::post('upload_pic', 'UploadController@storePhoto');

Here is my code for the php laravel template:

            <div >
            <form action="{{url('/upload_pic')}}" method="post" enctype="multipart/form-data">
                {{csrf_field()}}
                <div >
                    <label for="upload-user-photo">Upload Photos</label>
                    <input type="file" name="image"  placeholder="Upload Student Image, Size:207(W)x408(H)">
                </div>
                <div >
                    <div >
                        <input  type="submit" value="Upload Student Photo" name="submit">
                    </div>
                </div>

            </form>
        </div>

Here is my code in the controller:

    public function storePhoto(Request $request){
    $valid = $request->validate([
        'image' => 'required|image|mimes:jpg,png,jpeg,|dimensions:max_width=272,max_height=408,min_width=271,min_height=407'
    ]);
    $data = new Postimage();
    $file = $request->file('image');
    $filename = $file->getClientOriginalName();
    // dd($filename);
    $file -> move(public_path('./public/img/student_photos'),$filename);
    $data['image'] = $filename;
    $data->save();
    return redirect('/upload')->with('success', 'Photo Uploaded');
}

CodePudding user response:

Your problem is somewhere here

$filename = $file->getClientOriginalName();
$file -> move(public_path('./public/img/student_photos'),$filename);
  • First, the file comprises only the file extension. Instead, you should have something like this $filename = 'name.' . $file->getClientOriginalName(); Notice the dot in 'name.'
  • Secondly, no need to add public to the file path string. So it should be $file->move(public_path('img/student_photos'),$filename);
  • Finally, make sure the upload folder exists and is writeable
  • Related