FileService.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace app\common\service;
  3. use app\common\service\Service;
  4. use think\facade\Filesystem;
  5. use think\facade\Request;
  6. use think\facade\Validate;
  7. class FileService extends Service
  8. {
  9. /**
  10. * 上传图片
  11. * 本地运行如果无法写入图片可能是没有给public目录写权限
  12. *
  13. * @param string $path 上传路径,默认为'default'
  14. * @return array 上传后的图片路径
  15. */
  16. public function uploadImage($path = 'default')
  17. {
  18. // 获取表单上传文件
  19. $files = request()->file();
  20. // 验证上传文件格式和大小
  21. $this->validate($files, Validate::rule(['file' => 'fileSize:2048000|fileExt:jpeg,jpg,png,webp']));
  22. $file = request()->file('file');
  23. try {
  24. // 保存上传文件到public目录下的$path目录中
  25. $path = Filesystem::disk('public')->putFile($path, $file);
  26. } catch (\Exception $e) {
  27. throw $this->warpException($e, '上传图片失败:\n');
  28. }
  29. // 获取图片的url地址
  30. $path = Request::domain() . getVirRootDir() . '/storage/' . $path;
  31. return [
  32. 'path' => $path
  33. ];
  34. }
  35. /**
  36. * 获取当前网站的域名地址
  37. *
  38. * @return string 域名地址
  39. */
  40. protected static function get_domain()
  41. {
  42. $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
  43. return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
  44. }
  45. }