【问题标题】:Image doesn't save in public folder laravel图像不保存在公用文件夹 laravel
【发布时间】:2020-10-03 19:40:34
【问题描述】:

我正在学习 laravel,但现在图像有问题, 我希望它保存在 storage/app/public/avatar 中以便我可以显示它,但它一直保存在 storage/app/avatar 中

我在 .env 中写了这个

FILESYSTEM_DRIVER=public

然后我生成存储链接

php artisan storage:link 

但还是一样,每次我上传照片时,它都会将其保存在存储/应用程序/头像中

谁能帮帮我?

在文件系统.php中

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

这里:

 $attributes['avatar'] = request('avatar')->store('public/avatars');

在 USer.php 中

public function getAvatarAttribute($value)
{
    return asset($value);
}

当我使用随机头像链接时,此方法可以正常工作, 但现在它什么也没显示,我检查了我的数据库,链接在那里,而且是正确的

public function getAvatarAttribute($value)
 {
    asset('storage/avatars/'.$image->name);
 }

$attributes['avatar'] = request('avatar')->store('public/avatars');

在控制器中,更新方法:

    $user->update($attributes);
    $user->password = Hash::make($user['password']);
    $user->save();
    return redirect($user->path());

在show.blade中

 <img
            src= "{{ $user->avatar }}"
            alt=""
            class="rounded-full mr-4 absolute"
            style="width: 150px; left: calc(50% - 75px); top: 300px"
        >

但是 src 变成了“(未知)”

【问题讨论】:

  • 嗨,阿里,你能把你的代码显示在你试图保存图像的地方吗?
  • 你觉得我应该写 store('public/avatars') 吗?
  • 是的!可能利用$image-&gt;move($filepath,$filename);
  • 好的,我把它更新到store('public/avatars'),它的工作,但现在我没有在网站上显示图像,我会更新代码
  • 你还需要保存图片的url。或assert('/avatars/filename.file-ext')

标签: php laravel


【解决方案1】:

这看起来更像是配置缓存问题,因为您的文件系统看起来配置正确。

storage/app 文件夹是 laravel 默认磁盘的路径(local 磁盘)。由于您已指定使用 public 作为 .env 中的默认磁盘,但您的应用程序仍在使用本地磁盘路径,这看起来像是缓存问题

尝试使用

php artisan config:clear

然后尝试

request('avatar')->store('avatars');

如果确实是缓存问题,那么文件应该存储在storage/app/public 文件夹中。

要获取图像的完整路径,请使用

Storage::url('avatar/'.$user->avatar);

所以在访问器中,使用

public function getAvatarAttribute($value)
{
    return Storage::url('avatar/'.$value);
}

不建议使用asset() 获取文件路径,因为如果有一天您希望将存储切换到云(S3 或任何其他存储)。基本上,您不想使用应用程序的存储文件夹),那么asset() 将不再为您提供正确的路径,您需要在任何地方进行更改。但是当使用 storage 门面时,你需要做的就是在 filesystems.php 中改变它

另外,为了自己测试,你也可以在存储时指定磁盘,通过指定磁盘作为store方法的第二个参数

request('avatar')->store('avatars', 'public');
Storage::disk('public')->url('avatar/'.$user->avatar);

【讨论】:

    【解决方案2】:

    store 方法将文件存储在 storage/app 目录中。这就是您的代码将图像存储在 storage/app/avatars

    中的原因
    request('avatar')->store('avatars');
    

    这会将其放在 storage/app/public/avatars 下

     request('avatar')->store('public/avatars');
    

    展示它

    asset('storage/avatars/`.$image->name)
    

    【讨论】:

    • 它可以工作,但它没有读取图像,我会更新代码
    猜你喜欢
    • 2017-07-26
    • 1970-01-01
    • 2018-03-24
    • 2017-07-22
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2021-04-27
    相关资源
    最近更新 更多