我编写了一个PHP脚本来强制下载文件给用户。一切都很好,只有一个例外,文件没有完全下载让我们说有一个10 MB的mp3文件下载,但它会在5 MB之后停止并显示下载完成。
我的网站托管服务商是godaddy.com
代码在下面
<?php
if(ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
if ( isset ( $_REQUEST['file_name'] )) {
$filename = basename($_REQUEST['file_name']);
$filesize = filesize("mp3gallery/".$_REQUEST['file_name']);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-length: $filesize");
header("Content-Transfer-Encoding: binary");
header('Content-type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3');
header('Content-Disposition: attachment; filename="'.$filename.'"');
$read_file = "mp3gallery/".$_REQUEST['file_name'];
function readfile_chunked($filename,$retbytes=true) {
$chunksize = 1*(1024*1024); // how many bytes per chunk
$buffer = '';
$cnt =0;
// $handle = fopen($filename, 'rb');
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
echo $buffer;
ob_flush();
flush();
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
readfile_chunked($read_file,true);
}
?>
请帮助.........
答案 0 :(得分:1)
答案 1 :(得分:0)
试试这个:
function download( $data , $fName ) {
header( sprintf( 'Expires: %s' , strftime( '%a, %d %b %Y %H:%M:%S GMT' , strtotime( '+1 year' , time() ) ) ) );
header( 'Cache-Control: no-cache, must-revalidate' );
header( 'Pragma: public, no-cache' );
header( sprintf( 'Content-Disposition: attachment; filename="%s"' , $fName ) );
header( sprintf( 'Content-Description: %s' , uniqid() ) );
if ( is_file( $data ) ) {
$filePath = sprintf( '%s/%s' , $_SERVER[ 'DOCUMENT_ROOT' ] , $data );
if ( file_exists( $data ) ) {
if ( version_compare( PHP_VERSION , '5.3.0' , '<' ) )
header( sprintf( 'Content-Type: %s' , mime_content_type( $filePath ) ) );
else
header( sprintf( 'Content-Type: %s' , finfo_file( finfo_open( FILEINFO_MIME_TYPE ) , $filePath ) ) );
header( sprintf( 'Content-Length: %d' , filesize( $filePath ) ) );
readfile( $data );
}
} else {
echo $data;
}
}