FileService.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. * 本地运行如果无法写入图片可能是没有给public目录写权限
  38. *
  39. * @param string $path 上传路径,默认为'default'
  40. * @return array 上传后的图片路径
  41. */
  42. public function uploadAttachment($path = 'default')
  43. {
  44. // 获取表单上传文件
  45. $files = request()->file();
  46. // 验证上传文件格式和大小
  47. $this->validate($files, Validate::rule(['file' => 'fileExt:pdf,doc,docx']));
  48. $file = request()->file('file');
  49. try {
  50. // 保存上传文件到public目录下的$path目录中
  51. $path = Filesystem::disk('public')->putFile($path, $file);
  52. } catch (\Exception $e) {
  53. throw $this->warpException($e, '上传图片失败:\n');
  54. }
  55. // 获取图片的url地址
  56. $path = Request::domain() . getVirRootDir() . '/storage/' . $path;
  57. return [
  58. 'path' => $path
  59. ];
  60. }
  61. /**
  62. * 获取当前网站的域名地址
  63. *
  64. * @return string 域名地址
  65. */
  66. protected static function get_domain()
  67. {
  68. $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
  69. return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
  70. }
  71. }