Allow specifying file name for uploaded files

This commit is contained in:
Elisha Witte
2021-08-24 17:34:13 +02:00
parent 3e674d0bef
commit 91c24cb313
3 changed files with 47 additions and 2 deletions
+12 -2
View File
@@ -4,6 +4,7 @@ namespace Filament\Forms\Concerns;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\FileUpload;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
@@ -83,8 +84,7 @@ trait CanUploadFiles
continue;
}
$storeMethod = $field->getVisibility() === 'public' ? 'storePublicly' : 'store';
$path = $temporaryUploadedFile->{$storeMethod}($field->getDirectory(), $field->getDiskName());
$path = $this->storeFile($temporaryUploadedFile, $field);
$this->syncInput($field->getName(), $path, false);
}
@@ -134,4 +134,14 @@ trait CanUploadFiles
throw $exception;
}
}
/**
* Store the given $file for the given $field in storage.
*/
protected function storeFile(UploadedFile $file, FileUpload $field): string
{
$storeMethod = $field->getVisibility() === 'public' ? 'storePublicly' : 'store';
return $file->{$storeMethod}($field->getDirectory(), $field->getDiskName());
}
}
@@ -5,4 +5,13 @@ namespace Filament\Resources\Forms\Components;
class FileUpload extends \Filament\Forms\Components\FileUpload
{
use Concerns\InteractsWithResource;
public $storeAsCallback;
public function storeAs(callable $storeAsCallback)
{
$this->storeAsCallback = $storeAsCallback;
return $this;
}
}
+26
View File
@@ -2,6 +2,11 @@
namespace Filament\Resources\Forms;
use Filament\Resources\Forms\Components\FileUpload;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Symfony\Component\HttpFoundation\ParameterBag;
trait HasForm
{
use \Filament\Forms\HasForm;
@@ -27,4 +32,25 @@ trait HasForm
{
return $form;
}
/**
* Store the given $file for the given $field in storage.
*/
protected function storeFile(UploadedFile $file, FileUpload $field): string
{
$storeMethod = $field->getVisibility() === 'public' ? 'storePublicly' : 'store';
if (! $field->getStoreAsCallback() || ! ($field->getLivewire()->record)) {
return $file->{$storeMethod}($field->getDirectory(), $field->getDiskName());
}
$record = $field->getLivewire()->record;
$input = new ParameterBag($record instanceof Model ? $record->attributesToArray() : $record);
return $file->{$storeMethod.'As'}(
$field->getDirectory(),
call_user_func($field->storeAsCallback, $file, $input),
$field->getDiskName()
);
}
}