Local.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php namespace Upload\Lib\Tool;
  2. use Dever;
  3. use Image\Lib\Tool;
  4. class Local
  5. {
  6. private $config;
  7. public function init($config)
  8. {
  9. $this->config = $config;
  10. }
  11. public function upload($type, $source, $dest, $chunk, $upload)
  12. {
  13. $file = Dever::file('upload/' . $dest);
  14. if ($chunk) {
  15. $chunk['file'] = $file;
  16. $file = Dever::file('upload/' . $dest . '_chunk/' . $chunk['cur'] . '.blob');
  17. }
  18. if ($type == 1) {
  19. if (!copy($source, $file)) {
  20. Dever::error('上传失败');
  21. }
  22. } elseif ($type == 2) {
  23. file_put_contents($file, $source);
  24. } else {
  25. Dever::error('上传类型无效');
  26. }
  27. if (!is_file($file)) {
  28. Dever::error('上传失败');
  29. }
  30. if ($chunk) {
  31. $dir = dirname($file);
  32. if (is_dir($dir)) {
  33. $files = scandir($dir);
  34. $num = count($files) - 2;
  35. if ($num == $chunk['total']) {
  36. $blob = '';
  37. foreach ($files as $k => $v) {
  38. if (strstr($v, '.blob')) {
  39. $temp = $dir . '/' . $v;
  40. $blob .= file_get_contents($temp);
  41. @unlink($temp);
  42. }
  43. }
  44. file_put_contents($chunk['file'], $blob);
  45. @rmdir($dir);
  46. $file = $chunk['file'];
  47. } else {
  48. return '';
  49. }
  50. } else {
  51. return '';
  52. }
  53. }
  54. $after = $upload->after();
  55. if ($after) {
  56. $tool = Dever::load(Tool::class)->get()->cover(true);
  57. foreach ($after as $k => $v) {
  58. if (isset($v['table'])) {
  59. $method = 'handle_' . $v['table'];
  60. $file = $this->$method($tool, $file, $v['param']);
  61. }
  62. }
  63. }
  64. return $this->url($file);
  65. }
  66. private function url($file)
  67. {
  68. $dest = str_replace(Dever::data() . DEVER_PROJECT . '/', '', $file);
  69. if ($this->config['host']) {
  70. return $this->config['host'] . $dest;
  71. }
  72. return Dever::host() . 'data/' . DEVER_PROJECT . '/' . $dest;
  73. }
  74. public function handle($id, $file, $type = 'thumb')
  75. {
  76. $param = Dever::db('image/' . $type)->find($id);
  77. $tool = Dever::load(Tool::class)->get()->cover(true);
  78. $file = $this->$method($tool, $file, $param);
  79. return $this->url($file);
  80. }
  81. private function handle_thumb($tool, $file, $param)
  82. {
  83. $tool->source($file);
  84. $result = $tool->thumb($param['width'] . '_' . $param['height']);
  85. if ($result) {
  86. return $result[0];
  87. }
  88. return $file;
  89. }
  90. private function handle_crop($tool, $file, $param)
  91. {
  92. $tool->source($file);
  93. $result = $tool->crop($param['width'] . '_' . $param['height'], $param['position']);
  94. if ($result) {
  95. return $result[0];
  96. }
  97. return $file;
  98. }
  99. }