2

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

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

包裹:

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

4

1 回答 1

4

您可以简单地定义文件系统配置$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()}";
}
}
于 2020-09-11T14:29:35.047 回答