Bootstrap

thinkphp:实现压缩文件上传、解压、文件更名、压缩包删除功能,增加trycatch

代码

public function upload_firstsure() {
    try {
        // 检查是否有文件上传
        if (!isset($_FILES['file']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {
            throw new \Exception('未接收到文件或文件上传失败');
        }

        // 获取上传的文件
        $uploaded_file = $_FILES['file']['tmp_name'];
        $file_true_name = $_FILES['file']['name'];

        // 获取当前日期
        $current_date = date("Ymd");

        // 动态创建文件夹
        $user_path = $_SERVER['DOCUMENT_ROOT'] . "/uploads/firstsure/{$current_date}/";
        if (!file_exists($user_path)) {
            if (!mkdir($user_path, 0777, true)) {
                throw new \Exception('创建文件夹失败');
            }
        }

        // 生成随机文件名
        $random_number = mt_rand(1000000000000000, 9999999999999999); // 随机生成16位数字
        $new_file_name = $current_date . '_' . $random_number . '.' . pathinfo($file_true_name, PATHINFO_EXTENSION);

        // 文件保存路径
        $move_to_file = $user_path . "/" . $new_file_name;

        // 调用压缩图片的方法
        if (!$this->compress_image($uploaded_file, $move_to_file)) {
            throw new \Exception('压缩或保存图片失败');
        }

        // 返回成功结果
        return json([
            'code' => 1,
            'msg' => '上传成功',
            'file_path' => "uploads/firstsure/{$current_date}/" . $new_file_name
        ]);
    } catch (\Exception $e) {
        // 返回失败结果
        return json([
            'code' => 0,
            'msg' => $e->getMessage()
        ]);
    }
}
private function compress_image($source_path, $destination_path) {
    try {
        // 设置最大文件大小为300KB
        $max_size = 307200;
        // 设置最小和最大质量
        $min_quality = 10;
        $max_quality = 90;

        // 获取图像信息
        list($width, $height, $type) = getimagesize($source_path);
        if (!$width || !$height) {
            throw new \Exception('无法获取图片信息');
        }

        // 创建图像资源
        switch ($type) {
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($source_path);
                break;
            case IMAGETYPE_PNG:
                $image = imagecreatefrompng($source_path);
                break;
            case IMAGETYPE_GIF:
                $image = imagecreatefromgif($source_path);
                break;
            default:
                throw new \Exception('不支持的图片格式');
        }

        // 初始化质量
        $quality = $max_quality;
        do {
            // 如果是PNG或GIF,我们不调整质量
            if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_GIF) {
                $success = ($type == IMAGETYPE_PNG) ? imagepng($image, $destination_path) : imagegif($image, $destination_path);
                $file_size = filesize($destination_path);
                break;
            }

            // 压缩JPEG图片并保存
            $success = imagejpeg($image, $destination_path, $quality);
            // 检查文件大小
            $file_size = filesize($destination_path);

            // 如果文件太大且质量还能降低,则降低质量再次尝试
            if ($file_size > $max_size && $quality > $min_quality) {
                $quality -= 5; // 每次减少5个点的质量以更精细地控制
                unlink($destination_path); // 删除之前生成的过大的图片
            } else {
                break;
            }
        } while ($quality >= $min_quality);

        // 清除内存中的图像资源
        imagedestroy($image);

        // 返回成功状态
        return $success;
    } catch (\Exception $e) {
        // 记录错误日志(可选)
        error_log('压缩图片失败: ' . $e->getMessage());
        return false;
    }
}

 参考

 php上传参考php:实现压缩文件上传、解压、文件更名、压缩包删除功能_php上传压缩包并解压-CSDN博客icon-default.png?t=O83Ahttps://blog.csdn.net/weixin_46001736/article/details/137605254?ops_request_misc=%257B%2522request%255Fid%2522%253A%25226ef920c24b1af44aaa9a421047266de2%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=6ef920c24b1af44aaa9a421047266de2&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-137605254-null-null.nonecase&utm_term=%E6%96%87%E4%BB%B6&spm=1018.2226.3001.4450

 

;