|
2 | 2 |
|
3 | 3 | namespace Unisharp\FileEntry; |
4 | 4 |
|
| 5 | +use League\Flysystem\FileNotFoundException; |
| 6 | +use Symfony\Component\HttpFoundation\File\UploadedFile; |
| 7 | + |
5 | 8 | class FileEntry |
6 | 9 | { |
| 10 | + protected $basepath; |
| 11 | + |
| 12 | + public function __construct($basepath = '/') |
| 13 | + { |
| 14 | + if (mb_substr($basepath, -1, 1, 'utf8') != '/') { |
| 15 | + $basepath .= '/'; |
| 16 | + } |
| 17 | + |
| 18 | + $this->basepath = $basepath; |
| 19 | + } |
| 20 | + |
| 21 | + public function save(UploadedFile $upload_file, $cus_name = null) |
| 22 | + { |
| 23 | + $file = $this->moveFile($upload_file, $cus_name); |
| 24 | + return $file; |
| 25 | + } |
| 26 | + |
| 27 | + private function moveFile($upload_file, $cus_name) |
| 28 | + { |
| 29 | + $suffix = $upload_file->getClientOriginalExtension(); |
| 30 | + $filename = uniqid() . '.' . $suffix; |
| 31 | + if (!empty($cus_name)) { |
| 32 | + $filename = $cus_name . '.' .$suffix; |
| 33 | + } |
| 34 | + \Storage::put( |
| 35 | + $this->basepath . $filename, |
| 36 | + file_get_contents($upload_file->getRealPath()) |
| 37 | + ); |
| 38 | + |
| 39 | + \File::delete($upload_file->getRealPath()); |
| 40 | + return $filename; |
| 41 | + } |
| 42 | + |
| 43 | + public function response($filename) |
| 44 | + { |
| 45 | + try { |
| 46 | + $path = $this->basepath . $filename; |
| 47 | + $file = \Storage::get($path); |
| 48 | + $filetime = \Storage::lastModified($path); |
| 49 | + $etag = md5($filetime); |
| 50 | + $time = date('r', $filetime); |
| 51 | + $expires = date('r', $filetime + 3600); |
| 52 | + if (trim(\Request::header('If-None-Match'), '\'\"') != $etag || |
| 53 | + new \DateTime(\Request::header('If-Modified-Since')) != new \DateTime($time) |
| 54 | + ) { |
| 55 | + return response($file, 200)->header('Content-Type', \Storage::mimeType($path)) |
| 56 | + ->setEtag($etag) |
| 57 | + ->setLastModified(new \DateTime($time)) |
| 58 | + ->setExpires(new \DateTime($expires)) |
| 59 | + ->setPublic(); |
| 60 | + } |
| 61 | + |
| 62 | + return response(null, 304)->setPublic(); |
| 63 | + } catch (FileNotFoundException $e) { |
| 64 | + abort(404); |
| 65 | + } |
| 66 | + } |
7 | 67 | } |
0 commit comments