如何在Spatie媒体库中更改图像目录?

时间:2020-09-11 12:51:40

标签: laravel spatie

我是这个包的新手,因为我通常使用图像干预。因此,问题在于每当我保存图像时,它都会保存在存储目录中而不是公共目录中。我试图查看文档并进行了一些研究,但未找到任何答案。请在下面查看我的代码以进行保存。

$user->addMediaFromRequest('avatar')->toMediaCollection('avatars');

包装:

https://spatie.be/docs/laravel-medialibrary/v7/introduction

1 个答案:

答案 0 :(得分:0)

您可以简单地使用$user->addMediaFromRequest('avatar')->toMediaCollection('avatars', 'disk');

定义文件系统配置。

如果以后需要的话,这里是即时通讯使用方式(简单用法)

在我的模型上:

use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\Models\Media;
class User extends Model implements HasMedia
{
use HasMediaTrait;
public function registerMediaCollections()
{
    $this
    ->addMediaCollection('avatar')
    ->singleFile()
    ->useDisk('public');
    ->useFallbackUrl(asset('/images/default-user.png'))
    ->useFallbackPath(public_path('/images/default-user.png'));
}

public function registerMediaConversions(Media $media = null)
{
    $this->addMediaConversion('avatar-thumb')->width(120)->height(120);
}
...

要使用模型访问器获取文件URL,请在我的模型中添加以下功能:

public function getAvatarAttribute()
{
    $file = $this->getMedia('avatar')->first();

    if($file) {
      $file->url = $file->getUrl();
      $file->thumbnail = $file->getUrl('avatar-thumb'));
      $file->alternate = $file->getCustomProperty('alternate') ?: $file->file_name;
    }else{
      $file = new \StdClass;
      $file->url = $this->getFallbackMediaUrl('avatar');
      $file->thumbnail = public_path('/images/default-user-thumb.png');
      $file->alternate = 'avatar.png';
    }

    return $file;
}

还使用自定义路径,在config \ medialibrary.php中设置此数组'path_generator' => Path\To\Your\Class::class,

然后上课:

use Spatie\MediaLibrary\Models\Media;
use Spatie\MediaLibrary\PathGenerator\PathGenerator as PathGenerators;

class PathGenerator implements PathGenerators
{
public function getPath(Media $media): string
{
    return $this->getBasePath($media).'/';
}

public function getPathForConversions(Media $media): string
{
    return $this->getBasePath($media).'/conversions/';
}

public function getPathForResponsiveImages(Media $media): string
{
    return $this->getBasePath($media).'/responsive-images/';
}

protected function getBasePath(Media $media): string
{
    //here im using trait to generate default path, e.g: path/mimes/avatar/media->id
    //its up to you to define folder structure, just make sure each folder
    //for conversions has unique name, or else it will be deleted
    $base_folder = $this->get_base_folder($media->mime_type);
    return "{$base_folder}/{$media->collection_name}/{$media->getKey()}";
}
}