4

我正在尝试通过流式下载通过我的服务器将文件下载给我。

这是我的脚本:

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=http://user:pass@example.com/file.bin';
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $r[2]);
ob_clean();
flush();
readfile($fileName);
exit;

example.com 不是我真正使用的,我只是不想显示真实的 URL。:) 当我在网络浏览器中访问此文件时,没有出现下载提示,也没有任何反应。$r[2]是文件的内容长度(以字节为单位),$fileName与附件标头中使用的 URL 相同。我真的不知道我做错了什么。

4

4 回答 4

5

读取文件();需要机器上文件的绝对路径而不是 url。

例如 /home/person/file.exe

于 2009-12-07T17:51:52.580 回答
0

文件名标题行的末尾缺少一个),但我假设在编辑该行时发生了这种情况。

对于它的价值,运行您的示例代码会给出下载提示,并没有真正测试过它,但也许它与服务器/客户端配置有关 - 而不是代码。

于 2009-12-07T17:52:56.403 回答
0

I found a way to download an image for example, but this could help with any kind of file. It downloads a file without using readfile.

I know it can be clumsy but sometimes we need some workarounds to get the job done.

Try this, where $src = 'http://external-server/remote-image.jpg'

$url_stuff = parse_url($src); 
$port = isset($url_stuff['port']) ? $url_stuff['port'] : 80; 
$fp = fsockopen($url_stuff['host'], $port); 
$query  = 'GET ' . $url_stuff['path'] . " HTTP/1.0\n"; 
$query .= 'Host: ' . $url_stuff['host']; 
$query .= "\n\n"; 
$buffer=null;
fwrite($fp, $query); 
while ($tmp = fread($fp, 1024)) 
{ 
    $buffer .= $tmp; 
} 

preg_match('/Content-Length: ([0-9]+)/', $buffer, $parts); 
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=your_file.bin');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');

$content = substr($buffer, - $parts[1]); 
echo $content;

this is tested and working ;-)

于 2012-12-27T00:01:35.580 回答
0

恕我直言,问题是文件大小,尝试通过 http 获取文件大小(查看此功能): http ://codesnippets.joyent.com/posts/show/1214

所以从编辑

header('Content-Length: ' . $r[2]);

header('Content-Length: ' . get_remote_file_size($fileurl) );

希望你能解决你的问题。

于 2011-05-19T10:02:05.527 回答