浏览代码

Merge pull request #1706 from laradocs/dev

上传文件添加 override 方法
Jiang Qinghua 3 年之前
父节点
当前提交
cdbdb5c270
共有 3 个文件被更改,包括 23 次插入5 次删除
  1. 0 3
      config/admin.php
  2. 11 1
      src/Form/Field/File.php
  3. 12 1
      src/Form/Field/UploadField.php

+ 0 - 3
config/admin.php

@@ -270,9 +270,6 @@ return [
             'file'  => 'files',
         ],
 
-        // Overwriting an existing file.
-        'override' => env('ADMIN_UPLOAD_OVERRIDE', false),
-
     ],
 
     /*

+ 11 - 1
src/Form/Field/File.php

@@ -17,7 +17,10 @@ class File extends Field implements UploadFieldInterface
     /**
      * @var array
      */
-    protected $options = ['events' => []];
+    protected $options = [
+        'events' => [],
+        'override' => false,
+    ];
 
     public function __construct($column, $arguments = [])
     {
@@ -227,4 +230,11 @@ class File extends Field implements UploadFieldInterface
             Helper::deleteContains($fieldRules, ['image', 'file', 'dimensions', 'size', 'max', 'min']);
         }
     }
+
+    public function override(bool $override = true)
+    {
+        $this->options['override'] = $override;
+
+        return $this;
+    }
 }

+ 12 - 1
src/Form/Field/UploadField.php

@@ -98,7 +98,7 @@ trait UploadField
      */
     public function renameIfExists(UploadedFile $file)
     {
-        if ($this->getStorage()->exists("{$this->getDirectory()}/$this->name") && ! config('admin.upload.override')) {
+        if ($this->getStorage()->exists("{$this->getDirectory()}/$this->name")) {
             $this->name = $this->generateUniqueName($file);
         }
     }
@@ -194,6 +194,10 @@ trait UploadField
 
         $this->name = $this->getStoreName($file);
 
+        if ($this->options['override']) {
+            $this->remove();
+        }
+
         $this->renameIfExists($file);
 
         $this->prepareFile($file);
@@ -216,6 +220,13 @@ trait UploadField
         throw new UploadException(trans('admin.uploader.upload_failed'));
     }
 
+    public function remove()
+    {
+        if ($this->getStorage()->exists("{$this->getDirectory()}/$this->name")) {
+            $this->getStorage()->delete("{$this->getDirectory()}/$this->name");
+        }
+    }
+
     /**
      * @param  UploadedFile  $file
      */