zoukankan      html  css  js  c++  java
  • PHP 如何以文件形式输出给前端

    一般WEB大部分通讯都是依靠HTTP来传输,HTTP规定了信息的组成部分。

    只要修改对应的返回HTTP头,就能告诉客户端返回的数据类型。

    废话不多说了,直接上代码。

    // 将路径文件输出给前端
    $filePath = './test.jpg';
    fileDownload($filePath);
    
    // 将程序的输出以文件形式输出
    //forceDownload('test.txt','你好呀');
    
    /**
     * 将服务器上的文件输出给前端
     *
     * @param $filePath
     * @return bool|false|int
     */
    function fileDownload($filePath)
    {
        if (false == file_exists($filePath)) {
            return false;
        }
    
        // http headers
        header('Content-Type: application-x/force-download');
        header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
        header('Content-length: ' . filesize($filePath));
    
        // for IE6
        if (false === strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6')) {
            header('Cache-Control: no-cache, must-revalidate');
        }
        header('Pragma: no-cache');
    
        // read file content and output
        return readfile($filePath);
    }
    
    /**
     * 将内容以文件形式输出
     *
     * @param string $filename
     * @param string $data
     * @return bool
     */
    function forceDownload($filename = '', $data = '')
    {
        if ($filename == '' OR $data == '') {
            return false;
        }
    
        if (false === strpos($filename, '.')) {
            return false;
        }
    
        $mime = 'application/octet-stream';
    
        // 用户使用是否IE
        if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== false) {
            $filename = rawurlencode($filename);
            header('Content-Type: "' . $mime . '"');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header("Content-Transfer-Encoding: binary");
            header('Pragma: public');
            header("Content-Length: " . strlen($data));
        } else {
            header('Content-Type: "' . $mime . '"');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header("Content-Transfer-Encoding: binary");
            header('Expires: 0');
            header('Pragma: no-cache');
            header("Content-Length: " . strlen($data));
        }
    
        exit($data);
    }
  • 相关阅读:
    洛谷P2219 [HAOI2007]修筑绿化带(单调队列)
    CF1059E Split the Tree(倍增)
    CF1059D Nature Reserve(二分)
    洛谷P4199 万径人踪灭(manacher+FFT)
    洛谷P2515 [HAOI2010]软件安装(tarjan缩点+树形dp)
    洛谷P4867 Gty的二逼妹子序列(莫队+树状数组)
    CF932E Team Work(第二类斯特林数)
    JZOJ4307. 【NOIP2015模拟11.3晚】喝喝喝
    洛谷 P2519 [HAOI2011]problem a
    构建秘钥对验证的SSH体系
  • 原文地址:https://www.cnblogs.com/caiawo/p/14468266.html
Copyright © 2011-2022 走看看