Skip to content
Advertisement

Why doesn’t my php laravel application store my image?

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 class="panel-body">
            <form action="{{url('/upload_pic')}}" method="post" enctype="multipart/form-data">
                {{csrf_field()}}
                <div class="form-group">
                    <label for="upload-user-photo">Upload Photos</label>
                    <input type="file" name="image" class="form-control" placeholder="Upload Student Image, Size:207(W)x408(H)">
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <input class="btn btn-success" 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');
}

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement