123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- <?php
- namespace crmeb\services\upload\storage;
- use crmeb\basic\BaseUpload;
- use crmeb\exceptions\UploadException;
- use think\exception\ValidateException;
- use think\facade\Config;
- use think\facade\Filesystem;
- use think\File;
- class Local extends BaseUpload
- {
-
- protected $defaultPath;
- public function initialize(array $config)
- {
- parent::initialize($config);
- $this->defaultPath = Config::get('filesystem.disks.' . Config::get('filesystem.default') . '.url');
- }
- protected function app()
- {
-
- }
-
- protected function uploadDir($path, $root = null)
- {
- if ($root === null) $root = app()->getRootPath() . 'public' . DS;
- return str_replace('\\', '/', $root . 'uploads' . DS . $path);
- }
-
- protected function validDir($dir)
- {
- return is_dir($dir) == true || mkdir($dir, 0777, true) == true;
- }
-
- public function move(string $file = 'file')
- {
- $fileHandle = app()->request->file($file);
- if (!$fileHandle) {
- return $this->setError('Upload file does not exist');
- }
- if ($this->validate) {
- try {
- validate([$file => $this->validate])->check([$file => $fileHandle]);
- } catch (ValidateException $e) {
- return $this->setError($e->getMessage());
- }
- }
- $fileName = Filesystem::putFile($this->path, $fileHandle);
- if (!$fileName)
- return $this->setError('Upload failure');
- $filePath = Filesystem::path($fileName);
- $this->fileInfo->uploadInfo = new File($filePath);
- $this->fileInfo->fileName = $this->fileInfo->uploadInfo->getFilename();
- $this->fileInfo->filePath = $this->defaultPath . '/' . str_replace('\\', '/', $fileName);
- return $this->fileInfo;
- }
-
- public function stream(string $fileContent, string $key = null)
- {
- if (!$key) {
- $key = $this->saveFileName();
- }
- $dir = $this->uploadDir($this->path);
- if (!$this->validDir($dir)) {
- return $this->setError('Failed to generate upload directory, please check the permission!');
- }
- $fileName = $dir . '/' . $key;
- file_put_contents($fileName, $fileContent);
- $this->fileInfo->uploadInfo = new File($fileName);
- $this->fileInfo->fileName = $key;
- $this->fileInfo->filePath = '/uploads/' . $this->path . '/' . $key;
- return $this->fileInfo;
- }
-
- public function delete(string $filePath)
- {
- if (file_exists($filePath)) {
- try {
- unlink($filePath);
- return true;
- } catch (UploadException $e) {
- return $this->setError($e->getMessage());
- }
- }
- return false;
- }
- }
|