• [php]文件下载简述


    文件下载是通过网页页面链接跳转到后台php脚本处理,前台跳转链接代码如下:

    <a href="download.php?filename=hello.txt">download</a>

    后台处理脚本

    <?php
        /*
            @param $file_name: filename
            @paramp $file_sub_path: file sub path
            @function download file
        */
        function down_file($file_name)
        {
            /*convert encode*/
            $file_name = iconv("utf-8", "gb2312", $file_name);
            $file_path = $_SERVER['DOCUMENT_ROOT'].$file_sub_path.$file_name;
            if(!file_exists($file_path))
            {
                echo "file not exist!</br>";
                return;
            }
            $fp = fopen($file_path, "r");
    
            /*get file length*/
            $file_size = filesize($file_path);
    
            /*change protocal to tell browser is download*/
    
            header("Content-type: application/octet-stream");
            header("Accept-Ranges: bytes");
            header("Accept-Length: $file_size");
            header("Content-Disposition: attachment; filename=".$file_name);
    
            /*transpot to brower*/
            /*file buffer*/
            $buffer = 10240;
            /*file counter*/
            $file_count = 0;
            while(!feof($fp) && ($file_size-$file_count>0))
            {
                $data = fread($fp, $buffer);
                $file_count+=$buffer;
                echo $data;
            }
    
            /*close file*/
            fclose($fp);
        }
        $file_name = $_REQUEST['filename'];
        down_file($file_path);
    ?>

    下载文件需要的四个header
    //告诉返回文件的类型,application/octet-stream表示不知道类型,为二进制流
    header("Content-type:application/octet-stream");
    //按字节返回
    header("Accept-Ranges:bytes");
    //返回文件的大小
    header("Accept-Length:$file_size");
    //返回的文件名称
    header("Content-Disposition:attachment; filenae=".filename);

  • 相关阅读:
    Elasticsearch 检索
    Elasticsearch 基本操作
    Elasticsearch 集群
    Elasticsearch 插件head和kibana
    Elasticsearch 安装
    CentOS 安装JDK
    前端登录密码加密传输
    springboot2.0 快速集成kafka
    原来自定义模型绑定器还可以这么玩
    Value cannot be null or empty. 参数名: contentPath
  • 原文地址:https://www.cnblogs.com/fantasy01/p/4272585.html
Copyright © 2020-2023  润新知