Fork me on Baidu

h5文件上传并且压缩文件

public function uploadImage()
    {
        // 获取 Base64 编码的文件数据
        $base64Data = $this->request->post('file');

        if (empty($base64Data)) {
            return json([
                'code' => 0,
                'message' => '没有文件上传'
            ]);
        }

        // 检查 Base64 数据大小(最大 2MB)
        $maxSize = 2 * 1024 * 1024; // 2MB
        $base64Size = strlen($base64Data); // Base64 数据大小
        $estimatedBinarySize = $base64Size * 0.75; // 估算原始二进制数据大小

        if ($estimatedBinarySize > $maxSize) {
            $this->error('图片大小不能超过 2MB');
        }

        // 去除 data URL 前缀(如果存在)
        if (preg_match('/^data:image\/(\w+);base64,/', $base64Data, $type)) {
            $base64Data = substr($base64Data, strpos($base64Data, ',') + 1);
        }
        // 解码 Base64 数据
        $decodedData = base64_decode($base64Data);

        if ($decodedData === false) {
            $this->error('Base64 解码失败');
        }

        // 生成文件名
        $extension = isset($type[1]) ? $type[1] : 'png'; // 默认为 png
        $fileName = date('Ymd', time()) . '/' . substr(\fast\Random::alnum(32), 0, 32) . '.' . $extension;
        $filePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . $fileName;

        $directory = dirname($filePath);
        if (!is_dir($directory)) {
            mkdir($directory, 0777, true);
        }

        // 保存文件
        if (file_put_contents($filePath, $decodedData)) {
            // 图片保存成功,进行压缩
            $yasuo_image_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'yasuo' . DS . $fileName;
            $yasuo_directory = dirname($yasuo_image_path);
            if (!is_dir($yasuo_directory)) {
                mkdir($yasuo_directory, 0777, true);
            }

            try {
                // 使用 think\Image 进行压缩
                $image = \think\Image::open($filePath);
                $image->thumb(150, 150)->save($yasuo_image_path);

                // 生成 CDN URL
                $all_path = cdnurl('/uploads/' . $fileName);
                $compressed_path = cdnurl('/uploads/yasuo/' . $fileName);



            } catch (\Exception $e) {
                $this->error('图片压缩失败: ' . $e->getMessage().$e->getLine().$e->getFile());
            }
        } else {
            $this->error('文件保存失败');
        }

        $data = [
            'file_path' => '/uploads/' . $fileName,
            'full_path' => $all_path,
            'compressed_path' => '/uploads/yasuo/' . $fileName,
            'compressed_full_path' => $compressed_path,
        ];
        $this->success('文件上传成功', $data);
    }

 

posted @ 2025-03-10 16:51  consideration  阅读(11)  评论(0)    收藏  举报