4 changed files with 93 additions and 4 deletions
@ -0,0 +1,69 @@ |
|||||
|
<?php |
||||
|
|
||||
|
namespace App\Http\Controllers\Admin; |
||||
|
|
||||
|
use App\Http\Controllers\Controller; |
||||
|
use App\Services\ApiResponseService; |
||||
|
use Exception; |
||||
|
use Illuminate\Http\JsonResponse; |
||||
|
use Illuminate\Http\Request; |
||||
|
use Illuminate\Support\Facades\Storage; |
||||
|
use Illuminate\Support\Facades\Validator; |
||||
|
use Illuminate\Validation\ValidationException; |
||||
|
|
||||
|
class UploadController extends Controller |
||||
|
{ |
||||
|
/** |
||||
|
* @var ApiResponseService |
||||
|
*/ |
||||
|
protected ApiResponseService $responseService; |
||||
|
|
||||
|
/** |
||||
|
* 构造函数 |
||||
|
* @param ApiResponseService $responseService |
||||
|
*/ |
||||
|
public function __construct( |
||||
|
ApiResponseService $responseService, |
||||
|
) { |
||||
|
$this->responseService = $responseService; |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* 上传图片 |
||||
|
* @param Request $request |
||||
|
* @return JsonResponse |
||||
|
* @throws ValidationException |
||||
|
*/ |
||||
|
public function uploadImage(Request $request): JsonResponse |
||||
|
{ |
||||
|
try { |
||||
|
$rules = [ |
||||
|
'image' => 'required|image|max:10240', // 10MB = 10240KB |
||||
|
]; |
||||
|
$messages = [ |
||||
|
'image.required' => __('upload.i_empty'), |
||||
|
'image.image' => __('upload.i_image'), |
||||
|
'image.max' => __('upload.i_max'), |
||||
|
]; |
||||
|
$validator = Validator::make($request->all(), $rules, $messages); |
||||
|
if ($validator->fails()) { |
||||
|
throw new ValidationException($validator); |
||||
|
} |
||||
|
$file = $request->file('image'); |
||||
|
$filename = time() . '_' . md5($file->getClientOriginalName()) . '.' |
||||
|
. $file->getClientOriginalExtension(); |
||||
|
$path = $file->storeAs('images', $filename, 'public'); |
||||
|
return $this->responseService->success( |
||||
|
['url' => Storage::url($path)] |
||||
|
); |
||||
|
} catch (ValidationException $e) { |
||||
|
throw $e; |
||||
|
} catch (Exception $e) { |
||||
|
return $this->responseService->systemError( |
||||
|
__('exception.upload.error') . ':' |
||||
|
. $e->getMessage() |
||||
|
); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
} |
||||
Loading…
Reference in new issue