简体   繁体   中英

Laravel Storing image file in public/storage/cover_images error

In PostController@store the code is:

public function store(PostFormRequest $request)
{
    if($request->hasFile('cover_image')){
        $filenamewithExt = $request->file('cover_image')->getClientOriginalName();
        $filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
        $extension = $request->file('cover_image')->getClientOriginalExtension();
        $fileNameToStore = $filename.'_'.time().'.'.$extension;
        $path = $request->file('cover_image')->storeAs('public/storage/cover_image',$fileNameToStore);
    }else{
        $fileNameToStore = 'noimage.jpg';
    }

    $post = new Posts();
    $post->title = $request->get('title');
    $post->category = $request->get('category');
    $post->body = $request->get('body');
    $post->cover_image = $fileNameToStore;
    $post->slug = Str::slug($post->title);

    $duplicate = Posts::where('slug', $post->slug)->first();
    if ($duplicate) {
        return redirect('new-post')->withErrors('Title already exists.')->withInput();
    }

    $post->author_id = $request->user()->id;
    if ($request->has('save')) {
        $post->active = 0;
        $message = 'Post saved successfully';
    } else {
        $post->active = 1;
        $message = 'Post published successfully';
    }
    $post->save();
    
    return redirect('edit/' . $post->slug)->withMessage($message);
}

The route at web.php is

 Route::post('new-post', 'PostController@store');
    

And the image upload option is at create.blade.php as:

  <form action="/new-post" method="post" enctype="multipart/form-data">
        .....
        <label for="myfile">Select image files:</label>
        <input type="file" id="cover_image" name="cover_image" multiple><br><br>
  </form>

The name of the image with timestamp is stored in the database table but it is not stored in directory public/storage/cover_images.

Take a look at your config/filesystems.php . First look what the default is set to. In my case for example it is set to:

'default' => env('FILESYSTEM_DRIVER', 'local'),

Since I have no FILESYSTEM_DRIVER in my .env file my default would be set to local.

Next take a look where the root of your local drive points to. In my case for example:

'local' => [
    'driver' => 'local',
    'root' => storage_path('app'),
],

So that means in my case it would be the base directory of my laravel project. Maybe your default drive is set to a cloud storage or something else and your files end up somewhere, where you don't expect them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM