Download.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Qii\Library;
  3. ignore_user_abort(true);
  4. class Download
  5. {
  6. const VERSION = 1.0;
  7. public function __construct()
  8. {
  9. }
  10. /**
  11. * 以字符串的形式下载文件
  12. *
  13. * @param String $fileName 保存的文件名
  14. * @param String $string 下载的内容
  15. */
  16. public function downloadByString($fileName, $string)
  17. {
  18. header('Cache-Control: max-age=2592000');
  19. header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
  20. header('Cache-Control: no-store, no-cache, must-revalidate');
  21. header('Cache-Control: pre-check=0, post-check=0, max-age=0');
  22. header("Content-type: application/octet-stream");
  23. header("Accept-Length: ". sizeof($string));
  24. $fileName = iconv("UTF-8", "GB2312//TRANSLIT", $fileName);
  25. header("Content-Disposition: attachment; filename=". $fileName);
  26. echo $string;
  27. }
  28. /**
  29. * 指定文件路径下载指定文件
  30. *
  31. * @param String $filePath 文件路径
  32. * @param String $fileName 文件名
  33. * @param String $mime 文件类型
  34. * @param String $view 下载/打开文件
  35. */
  36. public function download($filePath, $fileName = '', $mime = '', $view = 'download')
  37. {
  38. //设定不限制时间
  39. ignore_user_abort(false);
  40. set_time_limit(0);
  41. if(file_exists($filePath))
  42. {
  43. if($fileName == '')
  44. {
  45. $fileName = basename($filePath);
  46. }
  47. $file = fopen($filePath, "r"); // 打开文件
  48. // 输入文件标签
  49. header('Cache-Control: max-age=2592000');
  50. header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
  51. header('Cache-Control: no-store, no-cache, must-revalidate');
  52. header('Cache-Control: pre-check=0, post-check=0, max-age=0');
  53. if($mime != '' && $mime != 'unlink')
  54. {
  55. header("Content-type: {$mime}");
  56. }
  57. else
  58. {
  59. header("Content-type: application/octet-stream");
  60. }
  61. header('Content-Encoding: none');
  62. header('Content-Transfer-Encoding: binary');
  63. header("Accept-Ranges: bytes");
  64. header("Accept-Length: ". filesize($filePath));
  65. $fileName = iconv("UTF-8", "GB2312//TRANSLIT", $fileName);
  66. if($view == 'download')
  67. {
  68. header("Content-Disposition: attachment; filename=". $fileName);
  69. }
  70. else
  71. {
  72. header('Content-Disposition: inline;filename="'.$fileName.'"');
  73. }
  74. //输出固定长度的文件避免文件过大导致无法下载
  75. $chunk = 16384;
  76. $speed = 1000;
  77. //#$speed = 0;
  78. $sleep = $speed ? floor(( $chunk / ($speed*1024))*1000000) : 0;
  79. do
  80. {
  81. $buf = fread($file, $chunk);
  82. $sent += strlen($buf);
  83. echo $buf;
  84. ob_flush();
  85. flush();
  86. usleep($sleep);
  87. if(strlen($buf) ==0)
  88. {
  89. break;
  90. }
  91. }while(true);
  92. fclose($file);
  93. exit();
  94. }
  95. }
  96. }