$file_dir="upload/";
$file_name=$_GET['name']; //服务器的真实文件名
$file = fopen($file_dir . $file_name, "r "); // 打开文件
// 输入文件标签
Header( "Content-type: application/octet-stream ");
Header( "Accept-Ranges: bytes ");
Header( "Accept-Length: ".filesize($file_dir . $file_name));
Header( "Content-Disposition: attachment; filename= " .basename( $file_name));
// 输出文件内容
echo fread($file,filesize($file_dir . $file_name));
fclose($file);
exit;
做个补充:以下代码来源北邮人论坛它的功能是针对各种MIME类型文件在常用浏览器下直接能打开的下载。
$array=explode(".",$file_name);
$type=$array[count($array)-1];
switch($type) {
case 'jar': $mime = "application/java-archive"; break;
case 'zip': $mime = "application/zip"; break;
case 'jpeg': $mime = "image/jpeg"; break;
case 'jpg': $mime = "image/jpg"; break;
case 'jad': $mime = "text/vnd.sun.j2me.app-descriptor"; break;
case "gif": $mime = "image/gif"; break;
case "png": $mime = "image/png"; break;
case "pdf": $mime = "application/pdf"; break;
case "txt": $mime = "text/plain"; break;
case "doc": $mime = "application/msword"; break;
case "docx": $mime = "application/msword"; break;
case "ppt": $mime = "application/vnd.ms-powerpoint"; break;
case "wbmp": $mime = "image/vnd.wap.wbmp"; break;
case "wmlc": $mime = "application/vnd.wap.wmlc"; break;
case "mp4s": $mime = "application/mp4"; break;
case "ogg": $mime = "application/ogg"; break;
case "pls": $mime = "application/pls+xml"; break;
case "asf": $mime = "application/vnd.ms-asf"; break;
case "swf": $mime = "application/x-shockwave-flash"; break;
case "mp4": $mime = "video/mp4"; break;
case "m4a": $mime = "audio/mp4"; break;
case "m4p": $mime = "audio/mp4"; break;
case "mp4a": $mime = "audio/mp4"; break;
case "mp3": $mime = "audio/mpeg"; break;
case "m3a": $mime = "audio/mpeg"; break;
case "m2a": $mime = "audio/mpeg"; break;
case "mp2a": $mime = "audio/mpeg"; break;
case "mp2": $mime = "audio/mpeg"; break;
case "mpga": $mime = "audio/mpeg"; break;
case "wav": $mime = "audio/wav"; break;
case "m3u": $mime = "audio/x-mpegurl"; break;
case "bmp": $mime = "image/bmp"; break;
case "ico": $mime = "image/x-icon"; break;
case "3gp": $mime = "video/3gpp"; break;
case "3g2": $mime = "video/3gpp2"; break;
case "mp4v": $mime = "video/mp4"; break;
case "mpg4": $mime = "video/mp4"; break;
case "m2v": $mime = "video/mpeg"; break;
case "m1v": $mime = "video/mpeg"; break;
case "mpe": $mime = "video/mpeg"; break;
case "mpeg": $mime = "video/mpeg"; break;
case "mpg": $mime = "video/mpeg"; break;
case "mov": $mime = "video/quicktime"; break;
case "qt": $mime = "video/quicktime"; break;
case "avi": $mime = "video/x-msvideo"; break;
case "midi": $mime = "audio/midi"; break;
case "mid": $mime = "audio/mid"; break;
case "amr": $mime = "audio/amr"; break;
default: $mime = "application/force-download"; //强制下载
}
用 Header('Content-Type: '.$mime); 可替代上面Header( "Content-type: application/octet-stream "); 代码。
版权声明:《 PHP下载文件的代码总结 》为zhangkang原创文章,转载请注明出处!
最后编辑:2019-5-5 20:05:17