首页 > 后端开发 > php教程 > 任意格式文件下载

任意格式文件下载

WBOY
发布: 2016-07-25 08:46:01
原创
919 人浏览过
支持任意格式的文件下载
函数有两个参数,第一个参数是文件在服务器中完成路径,第二个参数是下载显示文件名称。
  1. /**
  2. * 下载文件
  3. * filename 不包括后缀名
  4. */
  5. public function download($_path, $filename = '') {
  6. if (file_exists($_path)) {
  7. $fullPath = CHtml::decode($_path);
  8. $filename = $filename ? $filename : substr(strrchr($fullPath, '/'), 1);
  9. // Parse Info / Get Extension
  10. $fsize = filesize($fullPath);
  11. $path_parts = pathinfo($fullPath);
  12. $ext = strtolower($path_parts["extension"]);
  13. $filename .= '.' . $ext;
  14. // Determine Content Type
  15. switch ($ext) {
  16. case 'apk':
  17. $ctype = 'application/vnd.android.package-archive';
  18. break;
  19. case 'chm':
  20. $ctype = 'application/octet-stream';
  21. break;
  22. case "pdf":
  23. $ctype = "application/pdf";
  24. break;
  25. case "txt":
  26. $ctype = "application/txt";
  27. break;
  28. case "zip":
  29. $ctype = "application/zip";
  30. break;
  31. case "doc":
  32. $ctype = "application/msword";
  33. break;
  34. case "xls":
  35. $ctype = "application/vnd.ms-excel";
  36. break;
  37. case "ppt":
  38. $ctype = "application/vnd.ms-powerpoint";
  39. break;
  40. case "gif":
  41. $ctype = "image/gif";
  42. break;
  43. case "png":
  44. $ctype = "image/png";
  45. break;
  46. case "jpeg":
  47. case "jpg":
  48. $ctype = "image/jpg";
  49. break;
  50. default:
  51. $ctype = "application/force-download";
  52. }
  53. $ua = $_SERVER["HTTP_USER_AGENT"];
  54. $encoded_filename = rawurlencode($filename);
  55. $encoded_filename = str_replace("+", "%20", $encoded_filename);
  56. header("Pragma: public"); // required
  57. header("Expires: 0");
  58. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  59. header("Cache-Control: private", false); // required for certain browsers
  60. header("Content-Type: $ctype");
  61. // header('Content-Disposition: attachment; filename="'.rawurlencode($filename).'"');
  62. if (preg_match("/MSIE/", $ua)) {
  63. header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
  64. } else if (preg_match("/Firefox/", $ua)) {
  65. header("Content-Disposition: attachment; filename*=utf8''" . $filename . '"');
  66. } else {
  67. header('Content-Disposition: attachment; filename="' . $filename . '"');
  68. }
  69. header("Content-Transfer-Encoding: binary");
  70. header("Content-Length: " . $fsize);
  71. ob_clean();
  72. flush();
  73. readfile($fullPath);
  74. } else {
  75. throw new Exception('文件不存在!', 1);
  76. }
  77. }
复制代码


相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板