FileModel.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace app\model;
  3. use think\Model;
  4. class FileModel extends Model
  5. {
  6. protected $name = "file";
  7. protected $pk = "id";
  8. function getPathAttr($value)
  9. {
  10. return joinPath("/", $value);
  11. }
  12. public static function addFile($file, $user_id = null)
  13. {
  14. $originPath = joinPath(public_path(), $file);
  15. $hash = hash_file('md5', $originPath);
  16. $find = self::where('hash', $hash)->find();
  17. if ($find) {
  18. if($find['path']!==$file){
  19. unlink($originPath);
  20. }
  21. return joinPath($find['path']);
  22. }
  23. if (file_exists($originPath)) {
  24. clearstatcache(true, $originPath);
  25. $info = [];
  26. $info["path"] = $file;
  27. $info["user_id"] = $user_id;
  28. $info['create_time'] = date("Y-m-d H:i:s");
  29. $info['size'] = filesize($originPath);
  30. $info['hash'] = $hash;
  31. $info["mime_type"] = mime_content_type($originPath);
  32. self::insert($info);
  33. return joinPath($info['path']);
  34. }
  35. return false;
  36. }
  37. static function delFile($path): bool
  38. {
  39. $path = joinPath(public_path(), $path);
  40. if (file_exists($path)) {
  41. $hash = hash_file("md5", $path);
  42. unlink($path);
  43. $find = self::where("hash", $hash)->find();
  44. if ($find) {
  45. $find->delete();
  46. }
  47. }
  48. return true;
  49. }
  50. static function moveFile($oldPath, $newPath): bool
  51. {
  52. $path = joinPath(public_path(), $oldPath);
  53. $Path2 = joinPath(public_path(), $newPath);
  54. if (file_exists($path)) {
  55. $find = self::where("hash", hash_file('md5', $path))->find();
  56. if ($find) {
  57. rename($path, $Path2);
  58. $find->path = joinPath('/', $newPath);
  59. $find->save();
  60. }
  61. }
  62. return true;
  63. }
  64. function user(): \think\model\relation\HasOne
  65. {
  66. return $this->hasOne(UserModel::class, "id", "user_id")->field("id,nickname,mail");
  67. }
  68. }