hyperf文件上传和url函数

2024年4月29日11:24:35

配置静态资源
如果您希望 Swoole 来管理静态资源,请在 config/autoload/server.php 配置中增加以下配置。

return [
    'settings' => [
        ...
        // 静态资源
        'document_root' => BASE_PATH . '/public',
        'enable_static_handler' => true,
    ],
];

控制器

public function uploadFile()
    {
        $file = $this->request->file('file');

        try {
            if ($file == null) {
                throw new Exception('未找到上传文件');
            }
            $data = CommonService::uploadFile($file, ['xls', 'xlsx', 'pdf', 'xls', 'xlsx', 'doc', 'docx', 'ppt', 'zip', 'pptx', 'mp4', 'flv'], 'file');

            return $this->success($data, '上传成功');
        } catch (Throwable $e) {
            return $this->fail($e);
        }
    }

需要引入 "zx/php-tools": "^0.0.1"

use Hyperf\HttpMessage\Upload\UploadedFile;
use ZX\Tools\File\MimeTypes;

//全局通用文件上传组件
    public static function uploadFile(UploadedFile $uploadedFile, array $acceptExt, string $fileType = 'image')
    {
        $ext = $uploadedFile->getExtension();
        p($ext);

        if (!in_array($ext, $acceptExt)) {
            throw new Exception('文件名后缀不允许');
        }
        //图片检测安全
        if ($fileType == 'image') {
            $res = self::checkMimeType($uploadedFile, $ext);
            if ($res == false) {
                throw new Exception('文件安全检测未通过');
            }
        }

        $date = date('Ymd');
        $filePath = GlobalCode::UPLOAD_URL . DIRECTORY_SEPARATOR . $fileType . DIRECTORY_SEPARATOR . $date . DIRECTORY_SEPARATOR;
        $allDir = 'public' . DIRECTORY_SEPARATOR . $filePath;
        p($allDir);

        if (!is_dir($allDir)) {
            if (!mkdir($allDir, 0755, true)) {
                throw new Exception('创建文件夹失败');
            }
        }

        $fileName = getToken() . '.' . $ext;
        $finalPath = BASE_PATH . DIRECTORY_SEPARATOR . $allDir . DIRECTORY_SEPARATOR . $fileName;
        $showPath = $filePath . DIRECTORY_SEPARATOR . $fileName;

        $uploadedFile->moveTo($finalPath);
        /*
         * 注意windows下返回的地址可能会出现双斜杠,linux不会
         * windows:http://www.la.com/upload\\image\\20230626\\15d092d9058b7c3ac1952c79ede5b411.jpg
         * linux:http://www.la.com/upload/image/20230626/15d092d9058b7c3ac1952c79ede5b411.jpg
         */
//        return $filePath . $fileName;

        return ['id' => uniqid(), 'src' => $showPath, 'fileName' => $fileName];
    }

    //检测文件是否合法
    public static function checkMimeType(UploadedFile $uploadedFile, string $ext = '')
    {
        try {
            $filePath = $uploadedFile->getRealPath();
            p($uploadedFile->getRealPath());

            $fileMimeType = mime_content_type($filePath);
            p($fileMimeType);
            $mimeTypes = MimeTypes::getImage();
            $isExist = array_key_exists($fileMimeType, $mimeTypes);

            if (!$isExist) {
                throw new Exception('非允许mime types类型');
            }

            list($width, $height, $type, $attr) = getimagesize($filePath, $ext);
            if ($width <= 0 || $height <= 0) {
                return false;
            } else {
                return true;
            }

        } catch (Exception $e) {
            return false;
        }

    }

url辅助函数返回请求的文件的全url

方案一:
abstract class AbstractController
{
    #[Inject]
    protected ContainerInterface $container;

    #[Inject]
    protected RequestInterface $request;

    #[Inject]
    protected ResponseInterface $response;

    /**
     * 生成快捷URL
     * @param string $str
     * @return void
     */
    public function to(string $str = '')
    {
        $scheme = $this->request->getUri()->getScheme() ?? 'http';
        $host = $this->request->getUri()->getHost() ?? '127.0.0.1';
        $port = $this->request->getUri()->getPort() ?? config('server.servers.port', 9500);

       $url = '';
        if ($port == 80 || $port == 443) {
            $url = "{$scheme}://{$host}/{$str}";
        } else {
            $url = "{$scheme}://{$host}:{$port}/{$str}";
        }
        return $url;
    }
}

方案二:
if (!function_exists('to')) {
    //快捷生成路径
    function to(string $str = '')
    {
        $request = ApplicationContext::getContainer()->get(RequestInterface::class);

        $scheme = $request->getUri()->getScheme() ?? 'http';
        $host = $request->getUri()->getHost() ?? '127.0.0.1';
        $port = $request->getUri()->getPort() ?? config('server.servers.port', 9500);

        $url = '';
        if ($port == 80 || $port == 443) {
            $url = "{$scheme}://{$host}/{$str}";
        } else {
            $url = "{$scheme}://{$host}:{$port}/{$str}";
        }
        return $url;
    }

}

posted on 2024-04-29 22:04  zh7314  阅读(62)  评论(0编辑  收藏  举报