salopot/laravel-attach-image

提供将文件附加到模型以及如果文件是图片时的操作功能

dev-master 2016-11-23 22:00 UTC

This package is not auto-updated.

Last update: 2024-09-23 13:38:53 UTC


README

提供将文件附加到模型以及如果文件是图片时的操作功能

特性

  • 使用laravel 文件系统/云存储来存储附加数据。现在支持:本地、FTP、Amazon S3、Rackspace、DropBox...
  • 支持Intervention Image库中任何图像处理操作
  • 可能在附加、获取内容、实时(处理格式不存储)时处理附加图像格式
  • 以数据URL的形式返回图像
  • 删除模型时自动删除附加文件

安装

安装此扩展的首选方式是通过 composer

使用以下命令通过composer安装此包

composer require salopot/laravel-attach-image "dev-master"

或添加

"salopot/laravel-attach-image": "dev-master"

到您的 composer.json 文件的 "require" 部分。

更新composer后,如果之前未使用,配置 图像处理器

配置 app/filesystems.php,在 "disks" 部分添加 "attach" 项

本地示例

'attach' => [
   'driver' => 'local',
   'root'   => base_path('public'),
   'baseUrl' => php_sapi_name() != 'cli' ?  asset('') : config('app.url'),
]

Amazon S3示例

'attach' => [
    'driver' => 's3',
    'key'    => 'your-key',
    'secret' => 'your-secret',
    'region' => 'your-region', //'eu-central-1' for Frankfurt
    'bucket' => 'your-bucket', //'testattach'
    'baseUrl' => 'https://s3.eu-central-1.amazonaws.com/testattach/'
 ]

用法

使用DB中的字符串字段存储附加数据的相对路径

Schema::create('books', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('sample');
    $table->string('cover');
    $table->timestamps();
});

扩展eloquent模型

use Illuminate\Database\Eloquent\Model;
use App\Helpers\FileAttach;
use App\Helpers\ImageAttach;

class Book extends Model
{
    protected $fillable = ['name', 'cover', 'sample'];

    protected $_sample;
    public function getSampleAttribute() {
        return $this->_sample ? : $this->_sample = new FileAttach($this, 'sample');
    }

    public function setSampleAttribute($value) {
        $this->getSampleAttribute()->attachFile($value);
    }

    protected $_cover;
    public function getCoverAttribute() {
        return $this->_cover ? : $this->_cover = new ImageAttach($this, 'cover', [
            'list' => [
                'on' => ImageAttach::PT_ATTACH,
                'process' => function($image, $imageAttach) {
                    $width = 100;
                    $height = 100;
                    return $image
                        ->resize($width, $height, function($constraint) {
                            $constraint->aspectRatio();
                        })
                        //->resizeCanvas($width, $height);
                        ->greyscale();
                },
            ],
            'thumb' => [
                'on' => ImageAttach::PT_ATTACH,
                'process' => function($image, $imageAttach) {
                    return $image
                        ->widen(500)
                        ->text('Sample text', (int)($image->width() / 2), (int)($image->height() / 2), function($font) {
                            $font->align('center');
                            $font->valign('center');
                            $font->color('#ff0000');
                        });
                },
            ],
        ]);
    }

    public function setCoverAttribute($value) {
        $this->getCoverAttribute()->attachFile($value);
    }

    public static function boot() {
        parent::boot();

        static::deleting(function($model) {
            /*
            $model->sample->clearData();
            $model->cover->clearData();
            */
            foreach($model->getMutatedAttributes() as $attribute) {
                if ($model->{$attribute} instanceof FileAttach) {
                    $model->{$attribute}->clearData();
                }
            }
            return true;
        });
    }

现在您可以使用模型的基本填充方法来附加上传的文件

class BookController extends Controller
{
...
    public function update(Request $request, $id)
    {
        $model = Book::findOrFail($id);
        //clear attach data functionality
        if ($request->has('clear_attach')) {
            if ($model->{$request->clear_attach} instanceof FileAttach) {
                $model->{$request->clear_attach}->clear();
                $model->save();
                return redirect()->to($this->getRedirectUrl())->withInput($request->input());
            }
        }
        $this->validate($request, [
            'name' => 'required|string|max:255',
            'sample' => 'mimes:pdf',
            'cover' => 'mimes:jpeg,png,bmp',
        ]);
        $model->fill($request->all())->save(); //store uploaded file to model
        return redirect()->route('book.show', ['id' => $id]);
    }

    public function destroy($id)
    {
        $model = Book::findOrFail($id);
        $model->delete();
        return redirect()->route('book.index');
    }

简单视图示例

{!! Form::open(['route' => 'book.store', 'files'=>true]) !!}
<form method="POST" action="book" enctype="multipart/form-data">
{{ csrf_field() }}

<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
    {!! Form::label('name', 'Name', ['class' => 'control-label']) !!}
    {!! Form::text('name', null, ['class' => 'form-control']) !!}
    @if ($errors->has('name'))
        <span class="help-block"><strong>{{ $errors->first('name') }}</strong></span>
    @endif
</div>
<div class="form-group{{ $errors->has('sample') ? ' has-error' : '' }}">
    {!! Form::label('sample', 'Sample', ['class' => 'control-label']) !!}
    @if(isset($model) && $model->sample->attached())
        <div style="vertical-align: middle">
            <a href="{{$model->sample->getUrl()}}"><span class="glyphicon glyphicon-paperclip" aria-hidden="true"></span></a>
            <button name="clear_attach" value="sample" class="btn btn-danger confirm" type="submit">
                Delete
            </button>
        </div>
    @else
        {!! Form::file('sample', ['accept'=>'.pdf']) !!}
        @if ($errors->has('sample'))
            <span class="help-block"><strong>{{ $errors->first('sample') }}</strong></span>
        @endif
    @endif
</div>
<div class="form-group{{ $errors->has('cover') ? ' has-error' : '' }}">
    {!! Form::label('cover', 'Cover', ['class' => 'control-label']) !!}
    @if(isset($model) && $model->cover->attached())
        <div style="vertical-align: middle">
            <img src="{{ $model->cover->getUrl('thumb') }}"/>
            <button name="clear_attach" value="cover" class="btn btn-danger confirm" type="submit">
                Delete
            </button>
        </div>
    @else
        {!! Form::file('cover', ['accept'=>'.png,.bmp,.jpg,.jpeg']) !!}
        @if ($errors->has('cover'))
            <span class="help-block"><strong>{{ $errors->first('cover') }}</strong></span>
        @endif
    @endif
</div>

<input class="btn btn-primary" type="submit" value="Save">
</form>