diff --git a/app/Http/Controllers/TopicsController.php b/app/Http/Controllers/TopicsController.php index c120594..01187e7 100644 --- a/app/Http/Controllers/TopicsController.php +++ b/app/Http/Controllers/TopicsController.php @@ -5,6 +5,7 @@ namespace App\Http\Controllers; use App\Http\Requests\TopicRequest; use App\Models\Category; use App\Models\Topic; +use App\Tools\ImageUploadTool; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; @@ -43,7 +44,30 @@ class TopicsController extends Controller public function edit(Topic $topic) { $this->authorize('update', $topic); - return view('topics.create_and_edit', compact('topic')); + $categories = Category::all(); + return view('topics.create_and_edit', compact('topic', 'categories')); + } + + public function uploadImage(Request $request, ImageUploadTool $imageUploadTool) + { + // 初始化返回数据,默认是失败的 + $data = [ + 'success' => false, + 'msg' => '上传失败!', + 'file_path' => '' + ]; + // 判断是否有上传文件,并赋值给 $file + if ($file = $request->upload_file) { + // 保存图片到本地 + $result = $imageUploadTool->save($request->upload_file, 'topics', \Auth::id(), 1024); + // 图片保存成功的话 + if ($result) { + $data['file_path'] = $result['path']; + $data['msg'] = "上传成功!"; + $data['success'] = true; + } + } + return $data; } public function update(TopicRequest $request, Topic $topic) diff --git a/resources/views/topics/create_and_edit.blade.php b/resources/views/topics/create_and_edit.blade.php index 98c1f19..56dd9aa 100644 --- a/resources/views/topics/create_and_edit.blade.php +++ b/resources/views/topics/create_and_edit.blade.php @@ -11,7 +11,15 @@ diff --git a/routes/web.php b/routes/web.php index 0be2bf5..4b1f863 100644 --- a/routes/web.php +++ b/routes/web.php @@ -33,3 +33,5 @@ Route::post('password/reset', 'Auth\ResetPasswordController@reset'); Route::resource('topics', 'TopicsController', ['only' => ['index', 'show', 'create', 'store', 'update', 'edit', 'destroy']]); Route::resource('categories', 'CategoriesController', ['only' => ['show']]); +Route::post('upload_image', 'TopicsController@uploadImage')->name('topics.upload_image'); +