OctoberCMS:检测是否上传了新图片

OctoberCMS: detect if new image uploaded

如何检测新图像是否已从后端表单上传到图库,以便我可以在保存之前对其进行操作。

我尝试了以下方法,但没有用:

<?php namespace Author\Plugin\Models;

use Model;

class ModelName extends Model
{
    public $attachMany = [
        'gallery' => 'System\Models\File',
    ];

    public function beforeSave()
    {
        if (Input::hasFile('gallery')) {
            trace_log('new files');
        } else {
            trace_log('no new files');
        }
    }
}

-- 它一直给我 no new files 消息,无论我是否上传新文件。

您可以使用此代码调整模型图像的大小

它有点棘手,因为它使用不同的绑定。

you can use this code in your plugin's plugin.php's boot method

use October\Rain\Database\Attach\Resizer;
// .. other code ...

public function boot() {

  \Hardik\SoTest\Models\Item::extend(function($model) {
    // for create time only
      $model->bindEvent('model.beforeCreate', function() use ($model) {

        $records = \October\Rain\Database\Models\DeferredBinding::where([
          'master_type' => 'Hardik\SoTest\Models\Item', // <- REPLACE WITH YOUR MODEL(ModelName)
          "master_field" => "picture", // <- REPLACE WITH ATTACHEMNT MODEL (gallery)
          "slave_type" => "System\Models\File",
          "session_key" => post('_session_key')
        ])->get();

        foreach($records as $record) {
          $fileRecord = \System\Models\File::find($record->slave_id);

          // code to resize image
          $width = 100;
          $height = 100;
          $options = []; // or ['mode' => 'crop']

          // just in place resize image
          Resizer::open($fileRecord->getLocalPath()) // create from real path
                    ->resize($width, $height, $options)
                    ->save($fileRecord->getLocalPath());
        }
      });
  });      
}

如有疑问请评论。