【问题标题】:Laravel Storing image file in public/storage/cover_images errorLaravel 将图像文件存储在 public/storage/cover_images 错误
【发布时间】:2020-10-31 22:44:46
【问题描述】:

在 PostController@store 中的代码是:

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);
}

web.php 处的路由是

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

图片上传选项在create.blade.php 为:

  <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>

带时间戳的图片名称存储在数据库表中,但不存储在目录public/storage/cover_images中。

【问题讨论】:

  • 错误是什么?
  • 图片不保存在目录中,显示在博客页面中。当我检查数据库时,会存储附加时间戳的图像文件的名称。

标签: php laravel image public


【解决方案1】:

看看你的config/filesystems.php。首先看看默认设置是什么。以我为例,它设置为:

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

由于我的.env 文件中没有FILESYSTEM_DRIVER,所以我的默认设置为本地。

接下来看一下本地驱动器的根目录指向的位置。以我为例:

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

所以这意味着在我的情况下,它将是我的 laravel 项目的基本目录。也许您的默认驱动器设置为云存储或其他东西,而您的文件最终会出现在您意想不到的地方。

【讨论】:

  • 是的,设置如您所述。然而问题并没有解决。
猜你喜欢
  • 1970-01-01
  • 2016-08-04
  • 2016-08-19
  • 1970-01-01
  • 2017-09-12
  • 2020-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
相关资源
最近更新 更多