Laravel中使用wangEditor
wangEditor是一個優秀的國產的輕量級富文字編輯器(雖然本人還是喜歡MarkDown,但是不是任何人都喜歡MarkDown這樣的編寫方式的),wangEditor和百度的UEditor相比,確實是要輕量很多,UEditor太過於臃腫而且編輯用起來很難做到格式的一個統一性。
本人現在在使用laravel-admin這個後臺的框架,感覺用起來還比較輕量級,中文文件充足。
建立一個Field的擴充套件
<?php
namespace App\Admin\Extensions;
use Encore\Admin\Form\Field;
class WangEditor extends Field
{
protected $view = 'admin.wangeditor';
protected static $css = [
'/packages/admin/wangEditor/dist/css/wangEditor.min.css',
];
protected static $js = [
'/packages/admin/wangEditor/dist/js/wangEditor.js',
];
public function render()
{
$editor_id = $this->id;
$z_index = 999999;
$printLog = config('wang-editor.printLog', 'true');
$uploadImgUrl = config('wang-editor.uploadImgUrl', '/admin/upload/uploadImg');
$mapAk = config('wang-editor.mapAk', 'TVhjYjq1ICT2qqL5LdS8mwas');
$pasteFilter = config('wang-editor.pasteFilter', 'false');
$pasteText = 'true';
if ($pasteFilter == 'true') {
$pasteText = config('wang-editor.pasteText', 'true');
}
$token = csrf_token();
$this->script = <<<EOT
var menus = [
'source',
'|',
'bold',
'underline',
'italic',
'strikethrough',
'eraser',
'forecolor',
'bgcolor',
'|',
'quote',
'fontfamily',
'fontsize',
'head',
'unorderlist',
'orderlist',
'alignleft',
'aligncenter',
'alignright',
'|',
'link',
'unlink',
'table',
'emotion',
'|',
'img',
'video',
// 'location',
'insertcode',
'|',
'undo',
'redo',
'fullscreen'
];
wangEditor.config.printLog = {$printLog};
var _{$editor_id} = new wangEditor('{$editor_id}');
_{$editor_id}.config.uploadImgUrl = "{$uploadImgUrl}";
_{$editor_id}.config.uploadParams = {
token : '{$token}'
};
_{$editor_id}.config.mapAk = '{$mapAk}';
_{$editor_id}.config.zindex = {$z_index};
var _pasteFilter = {$pasteFilter};
_{$editor_id}.config.pasteFilter = _pasteFilter;
if (_pasteFilter == true) {
_{$editor_id}.config.pasteText = {$pasteText};
}
_{$editor_id}.config.uploadImgFileName = 'wang-editor-image-file';
_{$editor_id}.create();
EOT;
return parent::render();
}
}
建立對應的blade view
<div class="form-group {!! !$errors->has($errorKey) ?: 'has-error' !!}">
<label for="{{$id}}" class="col-sm-2 control-label">{{$label}}</label>
<div class="col-sm-6">
@include('admin::form.error')
<textarea style="height:400px;max-height:500px;display: none" cols="5" class="form-control" id="{{$id}}" name="{{$name}}" placeholder="{{ $placeholder }}" {!! $attributes !!} >{{ old($column, $value) }}</textarea>
@include('admin::form.help-block')
</div>
</div>
bootstrap.php中註冊擴充套件
Form::extend('wangeditor', WangEditor::class);
呼叫這個wangeditor擴充套件
這個時候基本你就可以使用wangeditor編輯器,但是無法上傳圖片
public function postUploadPicture(Request $request)
{
if ($request->hasFile('wang-editor-image-file')) {
//
$file = $request->file('wang-editor-image-file');
$data = $request->all();
$rules = [
'wang-editor-image-file' => 'max:5120',
];
$messages = [
'wang-editor-image-file.max' => '檔案過大,檔案大小不得超出5MB',
];
$validator = Validator($data, $rules, $messages);
// $validator = $this->validate($data, $rules, $messages);
$res = 'error|失敗原因為:非法傳參';
if ($validator->passes()) {
$realPath = $file->getRealPath();
$destPath = 'uploads/content/';
$savePath = $destPath.''.date('Ymd', time());
is_dir($savePath) || mkdir($savePath); //如果不存在則建立目錄
$name = $file->getClientOriginalName();
$ext = $file->getClientOriginalExtension();
$check_ext = in_array($ext, ['gif', 'jpg', 'jpeg', 'png'], true);
if ($check_ext) {
$uniqid = uniqid().'_'.date('s');
$oFile = $uniqid.'o.'.$ext;
$fullfilename = '/'.$savePath.'/'.$oFile; //原始完整路徑
if ($file->isValid()) {
$uploadSuccess = $file->move($savePath, $oFile); //移動檔案
$oFilePath = $savePath.'/'.$oFile;
$res = $fullfilename;
} else {
$res = 'error|失敗原因為:檔案校驗失敗';
}
} else {
$res = 'error|失敗原因為:檔案型別不允許,請上傳常規的圖片(gif、jpg、jpeg與png)檔案';
}
} else {
$res = 'error|'.$validator->messages()->first();
}
}
return $res;
}
路由註冊一下和擴充套件中配置的路徑統一就可以使用上傳圖片了,不使用Laravel-admin框架的可以直接使用wangEditor:直接看這裡
後續使用後的更新
使用上面的上傳圖片感覺非常的不爽,圖片處理太弱了,都無法壓縮、水印、調整大小等等
推薦使用image.intervention處理圖片
<?php
namespace App\Admin\Controllers;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Str;
use Intervention\Image\ImageManagerStatic;
class UpLoadController extends Controller
{
use ModelForm;
/**
* Storage instance.
*
* @var string
*/
protected $storage = '';
protected $preUrl = '';
protected $useUniqueName = false;
/**
* File name.
*
* @var null
*/
protected $name = null;
/**
* Upload directory.
*
* @var string
*/
protected $directory = '';
/**
* 針對editor.md所寫的圖片上傳控制器
*
* @param Request $requst
* @return Response
*/
public function postUploadPicture(Request $request)
{
if ($request->hasFile('wang-editor-image-file')) {
//
$file = $request->file('wang-editor-image-file');
$data = $request->all();
$rules = [
'wang-editor-image-file' => 'max:5120',
];
$messages = [
'wang-editor-image-file.max' => '檔案過大,檔案大小不得超出5MB',
];
$validator = Validator($data, $rules, $messages);
// $validator = $this->validate($data, $rules, $messages);
$res = 'error|失敗原因為:非法傳參';
if ($validator->passes()) {
$realPath = $file->getRealPath();
$destPath = 'uploads/content/';
$savePath = $destPath.''.date('Y', time());
is_dir($savePath) || mkdir($savePath); //如果不存在則建立年目錄
$savePath = $savePath.'/'.date('md', time());
is_dir($savePath) || mkdir($savePath); //如果不存在則建立月日目錄
$name = $file->getClientOriginalName();
$ext = $file->getClientOriginalExtension();
$check_ext = in_array($ext, ['gif', 'jpg', 'jpeg', 'png'], true);
if ($check_ext) {
$uniqid = uniqid().'_'.date('s');
$oFile = $uniqid.'o.'.$ext;
$fullfilename = '/'.$savePath.'/'.$oFile; //原始完整路徑
if ($file->isValid()) {
$uploadSuccess = $file->move($savePath, $oFile); //移動檔案
$oFilePath = $savePath.'/'.$oFile;
$res = $fullfilename;
} else {
$res = 'error|失敗原因為:檔案校驗失敗';
}
} else {
$res = 'error|失敗原因為:檔案型別不允許,請上傳常規的圖片(gif、jpg、jpeg與png)檔案';
}
} else {
$res = 'error|'.$validator->messages()->first();
}
}
return $res;
}
public function postUploadImg(Request $request){
if ($request->hasFile('wang-editor-image-file')) {
//
$file = $request->file('wang-editor-image-file');
$data = $request->all();
$rules = [
'wang-editor-image-file' => 'max:5120',
];
$messages = [
'wang-editor-image-file.max' => '檔案過大,檔案大小不得超出5MB',
];
$validator = Validator($data, $rules, $messages);
// $validator = $this->validate($data, $rules, $messages);
$res = 'error|失敗原因為:非法傳參';
if ($validator->passes()) {
$ext = $file->getClientOriginalExtension();
$check_ext = in_array($ext, ['gif', 'jpg', 'jpeg', 'png'], true);
if ($check_ext) {
$this->disk(config('admin.upload.disk'));
$this->directory = 'content/'.date('Y', time()).'/'.date('md', time())."/";
$this->name = $this->getStoreName($file);
$this->renameIfExists($file);
$target = $this->directory.$this->name;
$this->storage->put($target, file_get_contents($file->getRealPath()));
$this->storage->makeDirectory($this->directory.'/s300/');
$localPath = $this->storage->getDriver()->getAdapter()-> getPathPrefix();
//--------------寬度過大-------------------
$image = ImageManagerStatic::make($localPath.$target);
if($image->width()>600){
$image->resize(600, null, function ($constraint) {
$constraint->aspectRatio();
});
}
//--------------新增水印-------------------
$image->insert(public_path('/img/logo.png'), 'bottom-right', 15, 10);
$namearr = explode('.', $this->name);
$image->save($localPath.$this->directory.$namearr[0].'_logo.'.$namearr[1]);
//-------------縮圖----------------------
if($image->width()>$image->height()){
$image->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
});
}else{
$image->resize(null, 300, function ($constraint) {
$constraint->aspectRatio();
});
}
$image->save($localPath.$this->directory.'/s300/'.$namearr[0].'_logo.'.$namearr[1]);
if ($file->isValid()) {
// $res = $this->objectUrl($target);
$res = $this->objectUrl($this->directory.$namearr[0].'_logo.'.$namearr[1]);
} else {
$res = 'error|失敗原因為:檔案校驗失敗';
}
} else {
$res = 'error|失敗原因為:檔案型別不允許,請上傳常規的圖片(gif、jpg、jpeg與png)檔案';
}
} else {
$res = 'error|'.$validator->messages()->first();
}
}
return $res;
}
public function disk($disk)
{
$this->storage = Storage::disk($disk);
return $this;
}
public function renameIfExists(UploadedFile $file)
{
if ($this->storage->exists("$this->directory/$this->name")) {
$this->name = $this->generateUniqueName($file);
}
}
/**
* Get store name of upload file.
*
* @param UploadedFile $file
*
* @return string
*/
protected function getStoreName(UploadedFile $file)
{
if ($this->useUniqueName) {
return $this->generateUniqueName($file);
}
if (is_callable($this->name)) {
$callback = $this->name->bindTo($this);
return call_user_func($callback, $file);
}
if (is_string($this->name)) {
return $this->name;
}
return $file->getClientOriginalName();
}
public function objectUrl($path)
{
if (Str::startsWith($path, ['http://', 'https://'])) {
return $path;
}
if($this->preUrl == ''){
$url = config('admin.upload.host');
}else{
if(count(explode($this->preUrl,$path))>1){
$url = config('admin.upload.host');
}else{
$url = config('admin.upload.host').$this->preUrl;
}
}
return rtrim($url, '/').'/'.trim($path, '/');
}
protected function generateUniqueName(UploadedFile $file)
{
return md5(uniqid()).'.'.$file->guessExtension();
}
}
相關文章
- laravel中使用WangEditor及多圖上傳Laravel
- laravel中使用WangEditor及多圖上傳(下篇)Laravel
- vue中正確使用富文字編輯器wangeditor和使用wangeditor遇到的坑Vue
- Laravel 中 offset,limit 的使用LaravelMIT
- laravel使用中遇到的問題Laravel
- Laravel 中模型事件 Observer 的使用Laravel模型事件Server
- HTML 頁面使用 wangeditor 富文字編輯器HTML
- laravel-admin 富文字編輯器擴充套件 wangEditor V4版Laravel套件
- 直播原始碼開發,laravel-admin整合wangEditor2及上傳圖片原始碼Laravel
- vue2.0中引入wangEditor2步驟與坑Vue
- 聊聊 Interface 在 Laravel 開發中的使用Laravel
- Laravel 中 offset,limit 或 skip , take 的使用LaravelMIT
- 在 Laravel 中不用 Node / npm 使用 Tailwind CSSLaravelNPMAICSS
- 富文字編輯器:UEditor與wangEditor 初使用總結
- WangEditor遇到的問題
- Laravel 事務中 使用 悲觀鎖 小結Laravel
- 如何在 Laravel 中靈活的使用 TraitLaravelAI
- Redis 哨兵使用以及在 Laravel 中的配置RedisLaravel
- 在Laravel5.5中使用搜尋 ElasticsearchLaravelElasticsearch
- Laravel5.6中使用Laravel/Excel實現Excel檔案匯出功能LaravelExcel
- Vue3學習(二十)- 富文字外掛wangeditor的使用Vue
- Laravel-admin 配置 wangEditor3 富文字編輯器圖片七牛雲上傳Laravel
- Laravel10,Laravel廣播,Laravel-echo使用Laravel
- Laravel 中使用 Laravel-Excel 美化LaravelExcel
- Laravel 中 sql 查詢 使用 group by 報錯問題。LaravelSQL
- 分享一個Laravel中的管道的使用例項Laravel
- Laravel 使用 RedisLaravelRedis
- laravel rabbitmq 使用LaravelMQ
- Laravel Policy 使用Laravel
- laravel使用EasyWeChat 使用Laravel
- Laravel中的ModelLaravel
- wangEditor上傳圖片問題
- wangEditor——輕量化web富文字框Web
- 輕量級web富文字框——wangEditor使用手冊(1)——基本應用Web
- PHP trait 特性在 Laravel 中的使用個人心得PHPAILaravel
- 程式設計卡片 002 - Laravel 中如何使用 AdminLte程式設計Laravel
- 非 Laravel 專案中整合使用 illuminate/configLaravel
- Laravel 配合 jwt 使用LaravelJWT