V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lysS
V2EX  ›  服务器

PHP 文件下载,如果使用流下载的话前面不能有输出,所以各位大佬这应该怎么搞喃??

  •  
  •   lysS · 2019-12-02 18:07:07 +08:00 · 4310 次点击
    这是一个创建于 1599 天前的主题,其中的信息可能已经有所发展或是发生改变。
    function downLoad($file_path,$new_name)
    {
        if (file_exists($file_path)==FALSE){
            return 0;
        }
        $file=$file_path;
    	$fileinfo=finfo_open(FILEINFO_MIME_TYPE);
    	$mimeType=finfo_file($fileinfo,$file);
    	finfo_close($fileinfo);
    	header('Content-type:$mimeType');	//发送指定指定文件 MIME 类型的头信息报文
    	header('Content-Disposition:attachement;filename='."$new_name");	//文件名字 aaA.doc 
    	header('Content-Length:'.filesize($file));	//文件大小
        readfile($file);
    }
    downLoad("D:\\xampp\htdocs\aa.zip","aa.zip");
    

    必须使用流下载,因为有图片,不然浏览器会解析。
    好多这样的交互情景是下载的压缩包,比如下载个软件,难道他们自己放的链接??

    8 条回复    2019-12-03 09:28:32 +08:00
    dorentus
        1
    dorentus  
       2019-12-02 18:49:52 +08:00 via iPhone
    有 content-disposition:attachement 的 http header,浏览器就不会直接打开而是会提示下载了,不管是用 apache 还是 lighty 还是 nginx 或是 caddy,都可以很容易地给特定的 URL 的响应加上这个 header,根本不用走到 PHP 这里。
    callme
        2
    callme  
       2019-12-02 18:57:15 +08:00
    public function download($params){

    }
    ---------------------------------------------------
    我首先在服务器压缩好了文件,然后拿到服务器存储的文件名和文件路径,
    callme
        3
    callme  
       2019-12-02 18:57:58 +08:00
    public function download($params){
    $fileName = $params['fileName'];
    $downloadPath = $params['path'];
    header('Content-Type:application/x-compressed-tar;charset=utf-8');
    header('Content-disposition:attachment;filename='.$fileName);
    $filesize = filesize($downloadPath);
    readfile($downloadPath);
    header('Content-length:'.$filesize);
    unlink($downloadPath);
    }
    ---------------------------------------------------
    我首先在服务器压缩好了文件,然后拿到服务器存储的文件名和文件路径
    zsdsz
        4
    zsdsz  
       2019-12-02 19:00:01 +08:00 via Android
    ob_clean
    lysS
        5
    lysS  
    OP
       2019-12-02 21:50:10 +08:00
    @dorentus
    @callme
    知道如何下载,现在主要的矛盾是:必须用 header 下载,因为有图片文档格式;但是下载之前是有输出的,不然给用户一个空白的下载页也不好吧。
    而 header 之前是不能有输出的,html 也不行,矛盾就体现在这里!
    lysS
        6
    lysS  
    OP
       2019-12-02 21:58:16 +08:00
    @zsdsz 我前面也是定位到缓存这方面,想着清空缓存或者关闭缓存会有效果,但是前面有一个输出,它的默认 header 好像就变成了 text 了,后面要下载文件定义的 header 就失效了,即使是压缩包也会在浏览器上显示一堆乱码。。。
    dorentus
        7
    dorentus  
       2019-12-03 07:31:22 +08:00 via iPhone
    @lysS 下载前的页面要做成单独的页面
    lysS
        8
    lysS  
    OP
       2019-12-03 09:28:32 +08:00 via Android
    @dorentus 现在也只能这样了。。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1815 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:29 · PVG 00:29 · LAX 09:29 · JFK 12:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.