diff --git a/CHANGELOG.md b/CHANGELOG.md index c2724fd..86cbee1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ All notable changes to `laravel-upload` will be documented in this file. +### 1.0.0 +- Using this in production now. +- Added a storage saving method by only writing the file to the disk if it has a unique MD5. + ### 0.0.2 - Fixed tests. - Automatically saves model to DB. diff --git a/src/Upload.php b/src/Upload.php index 069aed1..dd9bdd6 100644 --- a/src/Upload.php +++ b/src/Upload.php @@ -18,20 +18,32 @@ public function __construct() public function create(UploadedFile $file) { - $disk = $this->config['disk']; - $filename = $this->getRandomString(32); - $extension = $file->extension(); - $directory = $this->getRandomDirectory(); - $contents = file_get_contents($file); - $mime = mime_content_type($file->path()); $fingerprint = md5_file($file->path()); - $path = "/{$directory}/{$filename}.{$extension}"; + $duplicate = File::where('fingerprint', $fingerprint)->first(); + + if (!$duplicate) { + $disk = $this->config['disk']; + $filename = $this->getRandomString(32); + $extension = $file->extension(); + $directory = $this->getRandomDirectory(); + $contents = file_get_contents($file); + $mime = mime_content_type($file->path()); - $result = $this->getDisk()->put($path, $contents); + $path = "/{$directory}/{$filename}.{$extension}"; - if ($result === false) { - throw new Exception("Could not save the file on the disk! Disk: ".$disk); + $result = $this->getDisk()->put($path, $contents); + + if ($result === false) { + throw new Exception("Could not save the file on the disk! Disk: ".$disk); + } + } else { + $filename = $duplicate->filename; + $mime = $duplicate->mime; + $path = $duplicate->path; + $disk = $duplicate->disk; + $extension = $duplicate->extension; + $fingerprint = $duplicate->fingerprint; } $model = new File(