我正在尝试使用下面的脚本下载大文件。该文件已下载,但其名称为“download”且缺少文件扩展名。如何修改下面的代码以保留原始文件名和扩展名?无论如何还要自动检测mime类型并包含它?
提前多多感谢。
$path = 'public/Uploads/Films/files/Crank2006.avi';
$size=filesize($path);
$fm=@fopen($path,'rb');
if(!$fm) {
// You can also redirect here
header ("HTTP/1.0 404 Not Found");
die();
}
$begin=0;
$end=$size;
if(isset($_SERVER['HTTP_RANGE'])) {
if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
$begin=intval($matches[0]);
if(!empty($matches[1])) {
$end=intval($matches[1]);
}
}
}
if($begin>0||$end<$size)
header('HTTP/1.0 206 Partial Content');
else
header('HTTP/1.0 200 OK');
header("Content-Type: video/avi");
header('Accept-Ranges: bytes');
header('Content-Length:'.($end-$begin));
header("Content-Disposition: inline;");
header("Content-Range: bytes $begin-$end/$size");
header("Content-Transfer-Encoding: binary\n");
header('Connection: close');
$cur=$begin;
fseek($fm,$begin,0);
while(!feof($fm)&&$cur<$end&&(connection_status()==0))
{ print fread($fm,min(1024*16,$end-$cur));
$cur+=1024*16;
usleep(1000);
}
die();
答案 0 :(得分:1)
在内容处置标题中,您需要指定文件名
$file_url = 'what you want to set'
header("Content-disposition: attachment; filename=\"" . $file_url. "\"");
这里强制下载php的好教程。
对于mime类型,请参阅以下SO帖子
答案 1 :(得分:0)
只需在$path
$path = 'public/Uploads/Films/files/Crank2006.avi';
$filename = array_pop(explode('/',$path)); // Grabbing the filename ... it will be Crank2006.avi
并将带有文件名的header
添加到现有标头中。
header("Content-disposition: filename=$filename");
修改强>
检测MIME类型...
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $filename);
答案 2 :(得分:0)
尝试下面的东西
$file='test.pdf' //File to download with Large Size
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
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: ' . filesize($file));
ob_clean();
flush();
readfile('backup/'.$file);
return 1;
} else {
return 0;
}