thinkphp预览文件服务接口封装

    /**
     * notes: 预览文件
     * api: previewFile
     * @return void
     * @author Harvey
     */
    public function previewFile()
    {
        $fileUrl = input('get.url');
        if (empty($fileUrl)) {
            echo '文件地址不能为空!';
            die;
        }
        //跳过https验证
        $stream_opts = [
            "ssl" => [
                "verify_peer" => false,
                "verify_peer_name" => false,
            ]
        ];
        $urlInfo = parse_url($fileUrl);
        $path = $urlInfo['path'];
        $extension = pathinfo($path, PATHINFO_EXTENSION);
        $fileContent = file_get_contents($fileUrl, false, stream_context_create($stream_opts));
        if ($extension == 'png') {
            header('Content-Type:image/png');
        } elseif ($extension == 'jpg' || $extension == 'jpeg') {
            header('Content-Type:image/jpeg');
        } elseif ($extension == 'pptx' || $extension == 'docx') {
            $href = 'https://view.officeapps.live.com/op/view.aspx?src=' . urlencode($fileUrl) . '&wdOrigin=BROWSELINK';
            $this->redirect($href);
        } elseif ($extension == 'pdf') {
            header('Content-Type: application/pdf');
            header('Content-Disposition: inline; filename="file.pdf"');
        } else {
            dump($extension);
            die;
        }
        if ($fileContent !== false) {
            echo $fileContent;
            exit();
        } else {
            echo '无法获取文件内容。';
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值