ホームページ  >  記事  >  バックエンド開発  >  任意の形式でファイルをダウンロードする

任意の形式でファイルをダウンロードする

WBOY
WBOYオリジナル
2016-07-25 08:46:01869ブラウズ
あらゆる形式のファイルのダウンロードをサポートします
この関数には 2 つのパラメーターがあります。最初のパラメーターはサーバー内のファイルのパスで、2 番目のパラメーターはダウンロードされたファイルの名前です。
  1. /**
  2. * ファイルをダウンロードします
  3. * ファイル名には接尾辞が含まれません
  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. // 情報を解析 / 拡張子を取得します
  10. $fsize = filesize($fullPath);
  11. $path_parts = pathinfo($ fullPath);
  12. $ext = strto lower($path_parts["extension"]);
  13. $filename .= '.' . $ext;
  14. // コンテンツ タイプを決定する
  15. switch ($ext) {
  16. case 'apk' :
  17. $ctype = 'application/vnd.android.package-archive';
  18. ブレーク;
  19. case 'chm':
  20. $ctype = 'application/octet-stream';
  21. ブレーク;
  22. case "pdf":
  23. $ctype = "アプリケーション/pdf";
  24. ブレーク;
  25. case "txt":
  26. $ctype = "アプリケーション/txt";
  27. ブレーク;
  28. case "zip":
  29. $ctype = "アプリケーション/zip";
  30. ブレーク;
  31. case "doc":
  32. $ctype = "application/msword";
  33. ブレーク;
  34. case "xls":
  35. $ctype = "application/vnd.ms-excel";
  36. ブレーク;
  37. case "ppt":
  38. $ctype = "application/vnd.ms-powerpoint";
  39. ブレーク;
  40. case "gif":
  41. $ctype = "image/gif";
  42. ブレーク;
  43. case "png":
  44. $ctype = "image/png";
  45. ブレーク;
  46. case "jpeg":
  47. case "jpg":
  48. $ctype = "image/jpg";
  49. ブレーク;
  50. デフォルト:
  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"); // 必須
  57. header("有効期限: 0");
  58. header("キャッシュコントロール: 必須再検証、事後チェック=0、事前チェック=0");
  59. ヘッダー("キャッシュコントロール: プライベート"、false); // 特定のブラウザに必要です
  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. flash();
  73. readfile($fullPath);
  74. } else {
  75. throw new Exception('ファイルが存在しません! ', 1);
  76. }
  77. }
コードをコピー


声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。