【问题标题】:How to avoid hard code in uploaded files path?如何避免上传文件路径中的硬代码?
【发布时间】:2021-09-11 02:49:27
【问题描述】:

我正在创建关于向用户上传头像的逻辑:

blade.php

<image src="{{ $user->profile->image ? storage_path() . '/  app/public/' . $user->profile->image : '' }}"/>
<input type="file" id="avatar" name="avatar"  style="display:none;"/>
<label for="avatar">{{ __('text.select_file') }}</label>

控制器(更新方法):

public function update(User $user)
{
    $this->authorize('update', $user->profile);

    $data = request()->validate([
        'name' => 'required',
    ]);

    if (request('avatar')) {
        $imagePath = request('avatar')->store('uploads/avatars', 'public');

        $image = Image::make(storage_path("app/public/{$imagePath}"))->fit(800, 800);
        $image->save();

        $imageArray = ['image' => $imagePath];
    }

    auth()->user()->profile->update(array_merge(
        $data,
        $imageArray ?? []
    ));

    return redirect("/profile/{$user->id}");
}

当我上传图片时,它存储在 storage/app/public/uploads/avatars 中,头像的 DB 值为 uploads/avatars/name.jpeg

如您所见,我在控制器和视图文件中有硬代码app/public/,这是默认情况下,我没有更改任何路径,这里是 filesystem.php:

<?php

return [

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

    'disks' => [

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

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
            'endpoint' => env('AWS_ENDPOINT'),
            'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
        ],

    ],

    'links' => [
        public_path('storage') => storage_path('app/public'),
    ],

];

那么我该如何避免这些编码路径呢?为什么 Laravel 默认存储文件夹在 storage 而不是 public 目录?我应该将头像上传到公共目录还是将它们留在存储中?我正在寻找最佳和正确的做法?

【问题讨论】:

    标签: php laravel laravel-8


    【解决方案1】:

    我不太精通 Laravel,但我认为您应该将所有可公开访问的内容存储在 /public/ 和 public_path():Difference between storing files in public directory and in storage in Laravel 5.4

    只需调用public_path($user-&gt;profile-&gt;image) 即可,但您可能需要在其中保留一些路径以确保头像位于它们自己的目录中。也许您可以编写另一个辅助函数:

    function avatar_path($filename){
      return public_path('avatars/'.$filename);
    }
    

    然后在任何地方使用avatar_path(),而不是storage_path()/public_path()。不过,我不确定这样简单的事情是否是“Laravel 方式”。

    【讨论】:

      猜你喜欢
      • 2011-01-07
      • 2012-02-26
      • 2018-11-19
      • 2013-09-09
      • 2021-06-05
      • 1970-01-01
      • 2022-10-31
      • 1970-01-01
      • 2016-09-10
      相关资源
      最近更新 更多