Skip to content

Commit 334894e

Browse files
committedDec 19, 2022
更新:编辑器优化,支持上传图片
·
v2.7.7v2.1.7
1 parent 74d27ee commit 334894e

File tree

6 files changed

+98
-45
lines changed

6 files changed

+98
-45
lines changed
 
Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,44 @@
11
<?php
22

3-
3+
declare(strict_types=1);
4+
/**
5+
* This file is part of zhuchunshu.
6+
* @link https://github.com/zhuchunshu
7+
* @document https://github.com/zhuchunshu/super-forum
8+
* @contact laravel@88.com
9+
* @license https://github.com/zhuchunshu/super-forum/blob/master/LICENSE
10+
*/
411
namespace App\Plugins\Core\src\Handler;
512

6-
713
use App\Plugins\User\src\Models\UserUpload;
814
use Illuminate\Support\Str;
915
use Intervention\Image\ImageManagerStatic as Image;
1016

1117
class UploadHandler
1218
{
13-
public function save($file, $folder, $file_prefix=null, $max_width = 1500): array
19+
public function save($file, $folder, $file_prefix = null, $max_width = 1500): array
1420
{
15-
if(!auth()->check()){
16-
if(!admin_auth()->Check()){
21+
if (! auth()->check()) {
22+
if (! admin_auth()->Check()) {
1723
return [
18-
'path' => "/404.jpg",
19-
"success" => false,
20-
"status" => "上传失败,未登录"
24+
'path' => '/404.jpg',
25+
'success' => false,
26+
'status' => '上传失败,未登录',
2127
];
2228
}
2329

2430
$user_id = 1;
25-
}else{
31+
} else {
2632
$user_id = auth()->id();
2733
}
28-
if(!$file_prefix){
34+
if (! $file_prefix) {
2935
$file_prefix = Str::random();
3036
}
3137
// 构建存储的文件夹规则,值如:uploads/images/avatars/201709/21/
3238
// 文件夹切割能让查找效率更高。
33-
$folder_name = "upload/$folder/" . date("Ym/d", time());
34-
if(!is_dir(public_path($folder_name))){
35-
mkdir(public_path($folder_name),0777,true);
39+
$folder_name = "upload/{$folder}/" . date('Ym/d', time());
40+
if (! is_dir(public_path($folder_name))) {
41+
mkdir(public_path($folder_name), 0777, true);
3642
}
3743
// 文件具体存储的物理路径,`public_path()` 获取的是 `public` 文件夹的物理路径。
3844
// 值如:/home/vagrant/Code/larabbs/public/uploads/images/avatars/201709/21/
@@ -45,25 +51,23 @@ public function save($file, $folder, $file_prefix=null, $max_width = 1500): arra
4551
// 值如:1_1493521050_7BVc9v9ujP.png
4652
$filename = $file_prefix . '_' . time() . '_' . Str::random(10) . '.' . $extension;
4753

48-
4954
// 将图片移动到我们的目标存储路径中
50-
$file->moveTo(public_path($folder_name."/".$filename));
55+
$file->moveTo(public_path($folder_name . '/' . $filename));
5156

5257
// 如果限制了图片宽度,就进行裁剪
5358
if ($max_width && $extension !== 'gif') {
54-
5559
// 此类中封装的函数,用于裁剪图片
5660
$this->reduceSize($upload_path . '/' . $filename, $max_width);
5761
}
5862
UserUpload::query()->create([
59-
"user_id" => $user_id,
60-
"path" => public_path("$folder_name/$filename"),
61-
"url" => "/$folder_name/$filename"
63+
'user_id' => $user_id,
64+
'path' => public_path("{$folder_name}/{$filename}"),
65+
'url' => "/{$folder_name}/{$filename}",
6266
]);
6367
return [
64-
'path' => "/$folder_name/$filename",
65-
"success" => true,
66-
"status" => "上传成功!"
68+
'path' => "/{$folder_name}/{$filename}",
69+
'success' => true,
70+
'status' => '上传成功!',
6771
];
6872
}
6973

@@ -74,7 +78,6 @@ public function reduceSize($file_path, $max_width)
7478

7579
// 进行大小调整的操作
7680
$image->resize($max_width, null, function ($constraint) {
77-
7881
// 设定宽度是 $max_width,高度等比例缩放
7982
$constraint->aspectRatio();
8083

@@ -85,4 +88,4 @@ public function reduceSize($file_path, $max_width)
8588
// 对图片修改后进行保存
8689
$image->save();
8790
}
88-
}
91+
}

‎app/Plugins/Topic/resources/views/create/basis.blade.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
<textarea name="basis[content]" id="basis-content" cols="30" rows="10"></textarea>
2626
</div>
2727

28+
<script src="{{file_hash("js/axios.min.js")}}"></script>
2829
<script defer>
2930
const target = document.getElementsByTagName("html")[0]
3031
const body_className = document.getElementsByTagName("html")[0].getAttribute("data-theme");
@@ -38,6 +39,25 @@
3839
3940
observer.observe(target, {attributes: true});
4041
42+
const image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
43+
const formData = new FormData();
44+
formData.append('file', blobInfo.blob(), blobInfo.filename());
45+
formData.append('_token', csrf_token);
46+
axios.post("/user/upload/image",formData,{
47+
'Content-type' : 'multipart/form-data'
48+
}).then(function(r){
49+
console.log(r)
50+
const data = r.data;
51+
if(data.success){
52+
resolve(data.result.url);
53+
return ;
54+
}
55+
reject({message:'HTTP Error: ' + data.result.msg + ', Error Code: '+data.code,remove: true});
56+
}).catch(function(e){
57+
console.log(e)
58+
})
59+
60+
});
4161
4262
document.addEventListener("DOMContentLoaded", function () {
4363
let options = {
@@ -54,6 +74,17 @@
5474
link_default_target: '_blank',
5575
toolbar_mode: 'sliding',
5676
image_advtab: true,
77+
automatic_uploads: true,
78+
images_reuse_filename: true,
79+
setup : function(ed) {
80+
//console.log(ed)
81+
},
82+
images_upload_handler: image_upload_handler,
83+
init_instance_callback: (editor) => {
84+
@if(request()->has('restoredraft'))
85+
editor.plugins.autosave.restoreDraft()
86+
@endif
87+
},
5788
mobile:{
5889
menu:{!! \App\Plugins\Topic\src\Lib\Editor::menu() !!},
5990
menubar:"{!! \App\Plugins\Topic\src\Lib\Editor::menubar() !!}",

‎app/Plugins/Topic/src/Controllers/TopicController.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,16 @@ public function create_post()
5050
return (new CreateTopic())->handler(request());
5151
}
5252

53+
#[PostMapping(path: 'create/upload')]
54+
#[Middleware(LoginMiddleware::class)]
55+
public function create_upload()
56+
{
57+
if (! Authority()->check('topic_create')) {
58+
return Json_Api(419, false, ['无发帖权限']);
59+
}
60+
return (new CreateTopic())->handler(request());
61+
}
62+
5363
#[PostMapping(path: 'create/draft')]
5464
#[Middleware(LoginMiddleware::class)]
5565

‎app/Plugins/Topic/src/Handler/Topic/Middleware/Create/CreateMiddleware.php

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,18 @@ public function handler($data, \Closure $next)
4545

4646
if ($validator->fails()) {
4747
// Handle exception
48-
return redirect()->with('danger', $validator->errors()->first())->url('topic/create')->go();
48+
$data = $data['basis'];
49+
unset($data['content']);
50+
$result = [];
51+
$result['basis']=$data;
52+
$result['restoredraft'] = true;
53+
return redirect()->with('danger', $validator->errors()->first())->url('topic/create?'.http_build_query($result))->go();
4954
}
50-
$this->create($data);
55+
$data = $this->create($data);
5156
return $next($data);
5257
}
5358

54-
public function create($data): void
59+
public function create($data)
5560
{
5661
// 帖子标题
5762
$title = $data['basis']['title'];
@@ -74,7 +79,7 @@ public function create($data): void
7479
'user_ip' => get_client_ip(),
7580
'user_agent' => get_user_agent(),
7681
]);
77-
$data = Topic::query()->create([
82+
$topic = Topic::query()->create([
7883
'post_id' => $post->id,
7984
'title' => $title,
8085
'user_id' => auth()->id(),
@@ -83,9 +88,12 @@ public function create($data): void
8388
'tag_id' => $tag,
8489
]);
8590
// 给Posts表设置topic_id字段的值
86-
Post::query()->where('id', $post->id)->update(['topic_id' => $data->id]);
87-
$this->topic_keywords($data, $_content);
88-
$this->at_user($data, $_content);
91+
Post::query()->where('id', $post->id)->update(['topic_id' => $topic->id]);
92+
$this->topic_keywords($topic, $_content);
93+
$this->at_user($topic, $_content);
94+
$data['topic_id']= $topic->id;
95+
$data['post_id']= $post->id;
96+
return $data;
8997
}
9098

9199
private function tag(string $html)

‎app/Plugins/User/src/Controller/ApiController.php

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
use App\Plugins\Core\src\Handler\FileUpload;
1414
use App\Plugins\Core\src\Handler\UploadHandler;
15+
use App\Plugins\User\src\Middleware\LoginMiddleware;
1516
use App\Plugins\User\src\Models\User;
1617
use App\Plugins\User\src\Models\UserFans;
1718
use App\Plugins\User\src\Models\UsersAuth;
@@ -20,36 +21,34 @@
2021
use App\Plugins\User\src\Models\UsersSetting;
2122
use App\Plugins\User\src\Models\UserUpload;
2223
use Hyperf\HttpServer\Annotation\Controller;
24+
use Hyperf\HttpServer\Annotation\Middleware;
2325
use Hyperf\HttpServer\Annotation\PostMapping;
2426
use Hyperf\RateLimit\Annotation\RateLimit;
25-
use Hyperf\Utils\Arr;
2627

2728
#[Controller]
2829
#[RateLimit(create: 1, capacity: 3)]
2930
class ApiController
3031
{
3132
#[PostMapping(path: '/user/upload/image')]
33+
#[Middleware(LoginMiddleware::class)]
3234
public function up_image(UploadHandler $uploader)
3335
{
34-
$data = [];
3536
if (! Authority()->check('upload_file')) {
3637
return Json_Api(419, false, ['msg' => '你所在的用户组无权上传图片']);
3738
}
38-
foreach (request()->file('file') as $key => $file) {
39-
if ($file->getSize() > get_options('core_user_up_img_size', 2048)) {
40-
$result = $uploader->save($file, 'topic', auth()->id());
41-
if ($result) {
42-
$url = $result['path'];
43-
$data['data']['succMap'][$url] = $url;
44-
} else {
45-
(array) $data['data']['errFiles'][] = $key;
46-
}
39+
$file = request()->file('file');
40+
if ($file->getSize() > get_options('core_user_up_img_size', 2048)) {
41+
$result = $uploader->save($file, 'topic', auth()->id());
42+
if ($result['success'] === true) {
43+
return Json_Api(200, true, ['msg' => '上传成功!', 'url' => $result['path']]);
4744
}
45+
return Json_Api(403, false, ['msg' => '上传失败!']);
4846
}
49-
return $data;
47+
return Json_Api(403, false, ['msg' => '上传失败!']);
5048
}
5149

5250
#[PostMapping(path: '/user/upload/file')]
51+
#[Middleware(LoginMiddleware::class)]
5352
public function up_file(FileUpload $uploader)
5453
{
5554
$data = [];
@@ -76,7 +75,7 @@ public function user_list(): array
7675
$data = User::query()->select('username', 'id')->get();
7776
$arr = [];
7877
foreach ($data as $key => $value) {
79-
$arr[$key]=['value' => '@' . $value->username, 'html' => '<img src="' . avatar_url($value->id) . '" alt="' . $value->username . '"/> ' . $value->username];
78+
$arr[$key] = ['value' => '@' . $value->username, 'html' => '<img src="' . avatar_url($value->id) . '" alt="' . $value->username . '"/> ' . $value->username];
8079
}
8180
return $arr;
8281
}
@@ -135,7 +134,7 @@ public function UserConfig(): array
135134
// 通知小红点
136135
$notice_red = 0;
137136
foreach (Itf()->get('users_notices') as $value) {
138-
$count = \Opis\Closure\unserialize((string)$value['count']);
137+
$count = \Opis\Closure\unserialize((string) $value['count']);
139138
if (@$count && is_callable($count) && call_user_func($count, auth()->id()) > 0) {
140139
$notice_red += call_user_func($count, auth()->id());
141140
}

‎public/js/axios.min.js

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)
Please sign in to comment.