Laravel-admin 整合 simditor

Fykex發表於2018-05-03
  • laravel5.5
  • laravel-admin 1.5.*
  • simditor 3.0.9

1. 建立Field擴充套件

namespace App\Admin\Extensions;

use Encore\Admin\Form\Field;

class Simditor extends Field
{
    protected $view = 'admin.simditor';

    protected static $css = [
        '/packages/simditor-2.3.6/styles/simditor.css',
    ];

    protected static $js = [
        '/packages/simditor-2.3.6/scripts/module.js',
        '/packages/simditor-2.3.6/scripts/hotkeys.js',
        '/packages/simditor-2.3.6/scripts/uploader.js',
        '/packages/simditor-2.3.6/scripts/simditor.js',

    ];

    public function render()
   {
       $name = $this->formatName($this->column);
       $token = csrf_token();
       $url = route('uploadImg');

       $this->script = <<<EOT
$(document).ready(function(){

      var editor = new Simditor({
          textarea: $('#editor'),
          toolbar: ['title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale', 'color', '|', 'ol', 'ul', 'blockquote', 'code', 'table', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent', 'alignment'],
          upload: {
                url: '$url',
                params: { _token: '$token'},
                fileKey: 'upload_file',
                connectionCount: 3,
                leaveConfirm: '檔案上傳中,關閉此頁面將取消上傳。'
            },
            pasteImage: true,
      });
 });
EOT;
       return parent::render();

   }
}

2. 建立對應檢視

<div class="form-group {!! !$errors->has($label) ?: 'has-error' !!}">

    <label for="{{$id}}" class="col-sm-2 control-label">{{$label}}</label>

    <div class="{{$viewClass['field']}}">

        @include('admin::form.error')

        <div id="{{$id}}" style="width: 100%; height: 100%;">
            <textarea name="body" id="editor" rows="3" placeholder="請填入至少三個字元的內容" required="required" class="form-control">{{ old($column, $value) }}</textarea>
        </div>
    </div>
</div>

3. bootstrap.php中註冊擴充套件

use App\Admin\Extensions\Simditor;
use Encore\Admin\Form;

Encore\Admin\Form::forget(['map', 'editor']);
Form::extend('seditor', Simditor::class);

4. 呼叫simditor

$form->seditor('body', '文章內容');

5. 圖片上傳(來自Laravel 教程 - Web 開發實戰進階 ( Laravel 5.5 )

  • 安裝Intervention/image擴充套件包
composer require intervention/image
  • 獲取配置資訊
php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5"
  • 建立工具類app/Handlers/ImageUploadHandler.php
namespace App\Handlers;

use Image;

class ImageUploadHandler
{
    protected $allowed_ext = ["png", "jpg", "gif", 'jpeg'];

    public function save($file, $folder, $file_prefix, $max_width = false)
    {
        // 構建儲存的資料夾規則,值如:uploads/images/avatars/201709/21/
        // 資料夾切割能讓查詢效率更高。
        $folder_name = "uploads/images/$folder/" . date("Ym/d", time());

        // 檔案具體儲存的物理路徑,`public_path()` 獲取的是 `public` 資料夾的物理路徑。
        // 值如:/home/vagrant/Code/larabbs/public/uploads/images/avatars/201709/21/
        $upload_path = public_path() . '/' . $folder_name;

        // 獲取檔案的字尾名,因圖片從剪貼簿裡黏貼時字尾名為空,所以此處確保字尾一直存在
        $extension = strtolower($file->getClientOriginalExtension()) ?: 'png';

        // 拼接檔名,加字首是為了增加辨析度,字首可以是相關資料模型的 ID
        // 值如:1_1493521050_7BVc9v9ujP.png
        $filename = $file_prefix . '_' . time() . '_' . str_random(10) . '.' . $extension;

        // 如果上傳的不是圖片將終止操作
        if ( ! in_array($extension, $this->allowed_ext)) {
            return false;
        }

        // 將圖片移動到我們的目標儲存路徑中
        $file->move($upload_path, $filename);

        // 如果限制了圖片寬度,就進行裁剪
        if ($max_width && $extension != 'gif') {

            // 此類中封裝的函式,用於裁剪圖片
            $this->reduceSize($upload_path . '/' . $filename, $max_width);
        }

        return [
            'path' => config('app.url') . "/$folder_name/$filename"
        ];
    }

    public function reduceSize($file_path, $max_width)
    {
        // 先例項化,傳參是檔案的磁碟物理路徑
        $image = Image::make($file_path);

        // 進行大小調整的操作
        $image->resize($max_width, null, function ($constraint) {

            // 設定寬度是 $max_width,高度等比例雙方縮放
            $constraint->aspectRatio();

            // 防止裁圖時圖片尺寸變大
            $constraint->upsize();
        });

        // 對圖片修改後進行儲存
        $image->save();
    }
}
  • 建立上傳控制器和相關路由
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Handlers\ImageUploadHandler;
use Auth;
use Log;

class UploadsController extends Controller
{
    public function uploadImg(Request $request, ImageUploadHandler $uploader)
       // 初始化返回資料,預設是失敗的
        $data = [
            'success'   => false,
            'msg'       => '上傳失敗!',
            'file_path' => ''
        ];
        // 判斷是否有上傳檔案,並賦值給 $file
        if ($file = $request->upload_file) {

            // 儲存圖片到本地
            $result = $uploader->save($request->upload_file, 'article', \Auth::guard('admin')->user()->id, 600);
            // 圖片儲存成功的話
            if ($result) {
                $data['file_path'] = $result['path'];
                $data['msg']       = "上傳成功!";
                $data['success']   = true;
            }
        }
        log::info($data);
        return $data;
   }
}
Route::post('uploadFile', 'UploadsController@uploadImg')->name('uploadImg');

6. 效果

file

相關文章