0

我试图编写一个脚本,用户可以通过该脚本直接下载图像。
这是我最终得到的代码,

   <?php
        $fileContents   =   file_get_contents('http://xxx.com/images/imageName.jpg');
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.urlencode("http://xxx.com/images/imageName.jpg"));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($fileContents));
        ob_clean();
        flush();
        echo $fileContents;
        exit;
    ?>

但是每次我在浏览器中点击上述脚本的 url 时,它都会返回一个零字节数据的文件。
你愿意帮我解决这个问题吗?

4

2 回答 2

0

试试下面的代码

<?php 
    $file_name = 'file.png';
    $file_url = 'http://www.myremoteserver.com/' . $file_name;
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"".$file_name."\""); 
    readfile($file_url);
?>

阅读更多,也阅读本教程

于 2013-01-18T06:19:19.380 回答
0

我注意到您在文件内容而不是文件名本身上使用了文件大小;

如果是,您的代码将起作用:

<?php
    $filename = 'http://xxx.com/images/imageName.jpg';
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.urlencode($filename));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filename));
    ob_clean(); // not necessary
    flush();  // not necessary
    echo file_get_contents($filename); // or just use readfile($filename);
    exit;
?>
于 2013-01-18T07:59:14.190 回答