Heim  >  Artikel  >  Backend-Entwicklung  >  任意格式文件下载

任意格式文件下载

WBOY
WBOYOriginal
2016-07-25 08:46:01868Durchsuche
支持任意格式的文件下载
函数有两个参数,第一个参数是文件在服务器中完成路径,第二个参数是下载显示文件名称。
  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. }
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn