sabbir268/laravel-filecaster

一个简单的用于处理文件上传和检索的 Laravel 模型转换类

v1.1.2 2023-11-15 12:48 UTC

This package is auto-updated.

Last update: 2024-09-15 14:43:57 UTC


README

一个简单的用于 Laravel 模型处理文件上传和检索的转换类

安装

composer require sabbir268/laravel-filecaster

配置

转换类别名 添加到别名数组中(可选)

'aliases' => Facade::defaultAliases()->merge([
    // ...
    'filecast' => Sabbir268\LaravelFileCaster\FileCaster::class,
    // ...
])->toArray(),

发布配置文件

php artisan vendor:publish --provider="Sabbir268\LaravelFileCaster\FileCasterServiceProvider"

从模型中使用

导入 FileCaster 类

use Sabbir268\LaravelFileCaster\FileCaster;

示例:管理 "image" 文件的上传和检索

假设,我们有一个 Blog 模型,其中有一个 image 列来存储图像文件。

use App\Models;
use Sabbir268\LaravelFileCaster\FileCaster;

class Blog extends Model
{
    // ...
    protected $casts = [
        'image' => FileCaster::class,
    ];
    // ...
}

或者,您可以使用 filecast 作为 Sabbir268\LaravelFileCaster\FileCaster 类的别名。

use App\Models;

class Blog extends Model
{
    // ...
    protected $casts = [
        'image' => 'filecast',
    ];
    // ...
}

现在当您创建一个新的 Blog 模型实例并且从请求中有一个文件分配给 image 属性时,它将自动将文件上传到 storage/app/public/{class_name}/{id} 目录,并将文件名和路径存储在 image 列中。

$blog = new Blog();
$blog->image = $request->file('image');
$blog->save();

当您检索模型实例时,它将自动从 image 列中检索文件路径,您可以使用它就像字符串一样。

$blog = Blog::find(1);
echo $blog->image; // output: /storage/blog/1/image.jpg

您可以使用几个方法和属性来检索文件信息。

// get file name
$blog->image->name; // output: image.jpg

// get file extension
$blog->image->extension; // output: jpg

// get file size
$blog->image->size; // output: 1024

// get image width
$blog->image->width; // output: 200

// get image height

$blog->image->height; // output: 200

// get file mime type
$blog->image->mime; // output: image/jpeg

// get file http url
$blog->image->url; // output: http://example.com/storage/blog/1/image.jpg

// get file full path
$blog->image->path; // output: /var/www/html/storage/app/public/blog/1/image.jpg

// get storage directory
$blog->image->dir; // output: /var/www/html/storage/app/public/blog/1

// check if file exists
$blog->image->exists; // output: true

如果您想获取处理过的图像 URL,可以使用 ur('WIDTHxHEIGHT') 方法。

$blog->image->url('200x200'); // output: http://example.com/storage/cache/200x200/blog-2-image1.jpg

注意:它将在存储缓存目录中创建处理过的图像。您需要在服务器上安装 gdimagick 扩展。

如果您想删除文件,可以使用 remove() 方法。

$blog->image->remove(); // output: true

贡献

您可以创建任何拉取请求。