UploadController.php 2.81 KB
<?php

namespace App\Http\Container\AppSection\Controllers;

use App\Helpers\JsonResource;
use App\Helpers\UploadHelper;
use App\Http\Container\AppSection\Requests\UploadReportRequest;
use App\Http\Container\AppSection\Requests\UploadRequest;
use App\Models\SystemUploadLog;
use Hikoon\LaravelApi\Support\ApiController;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;
use OSS\OssClient;

class UploadController extends ApiController
{

    /**
     * @param \App\Http\Container\AppSection\Requests\UploadRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \OSS\Core\OssException
     */
    public function __invoke(UploadRequest $request): JsonResponse
    {
        $type     = $request->get('contentType');
        $filePath = UploadHelper::getFileName(Str::before($type, '/')) . '.' . Str::afterLast($request->get('fileName'), '.');

        $signedUrl = UploadHelper::getOssSignUrl($filePath, [OssClient::OSS_CONTENT_TYPE => $type]);
        return JsonResource::success(JsonResource::SUCCESS, [
            'upload_url' => $signedUrl,
            'view_url'   => UploadHelper::getOssDomain() . parse_url($signedUrl, PHP_URL_PATH)
        ]);
    }

    /**
     * @param \App\Http\Container\AppSection\Requests\UploadRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function token(UploadRequest $request): JsonResponse
    {
        return JsonResource::success(JsonResource::SUCCESS, [
            'token'     => UploadHelper::getStsToken(),
            'domain'    => UploadHelper::getOssDomain(),
            'endpoint'  => UploadHelper::getOssEndpoint(true),
            'bucket'    => UploadHelper::getOssBucket(),
            'file_name' => UploadHelper::getFileName(Str::before($request->get('contentType'), '/')) . '.' . Str::afterLast($request->get('fileName'), '.')
        ]);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function stsToken(): JsonResponse
    {
        $uploadSts = UploadHelper::getStsToken();

        return JsonResource::success(JsonResource::SUCCESS, [
            'accessKeyId'     => $uploadSts->accessKeyId,
            'accessKeySecret' => $uploadSts->accessKeySecret,
            'stsToken'        => $uploadSts->securityToken,
            'stsExpire'       => 3000000,
            'region'          => UploadHelper::getOssEndpoint(true),
            'bucket'          => UploadHelper::getOssBucket(),
            'domain'          => UploadHelper::getOssDomain()
        ]);
    }

    /**
     * @param \App\Http\Container\AppSection\Requests\UploadReportRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function report(UploadReportRequest $request): JsonResponse
    {
        SystemUploadLog::query()->create($request->validated());

        return JsonResource::success('上报成功');
    }
}