zeroar/withfile

Laravel Livewire 的文件扩展。

v1.0 2020-05-03 20:59 UTC

This package is auto-updated.

Last update: 2024-09-04 11:24:43 UTC


README

Latest Stable Version Total Downloads License

简介

你在 livewire 组件中上传文件有问题吗?如果有,跟我一样。如果你使用 type file 的 input 并实现了 wire:model,这对你上传文件有用吗?目前还没有用。为什么会出现这种情况?因为 livewire 发送的是 json 数据,而不是表单数据。我不知道这个问题是否会在 livewire 的未来版本中得到解决。我研究了这个问题并找到了目前的解决方案。使用这个扩展,我希望它能解决这个问题。

安装

使用 composer 安装。

composer require zeroar/withfile

安装后,更新你的布局并在 @livewireScripts 后添加 @withfileScripts

    ...

    @livewireScripts
    @withfileScripts

</body>
</html>

组件实现

现在你可以在你的 livewire 组件中添加这个扩展。要实现它,请看下面的示例

namespace App\Http\Livewire;

use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Withfile\WithFile; // add this to implement

class UploadPhoto extends Component
{
use WithFile; // add this to implement
// this is target variable
// this variable will turn to array after upload file
public $photo;

    // please implement this variable and add the variable target
    // if you not implement this, WithFile will not working
    public $fileable = [
        'photo'
    ];

    public function render() {
        return view('livewire.upload-photo');
    }

    // implement this method to edit or save the file
    public function updatedPhoto($value, $old_value)
    {
        // in this area, you can implement what you want for the file.
        // to save the file, i recommend to try this for save file in local

        $filename = $value['name'];
        // below for customize filename
        // $filename = "custom-file-name" . $value['extension'];
        Storage::disk('public')->put($filename, $this->raw($value));

        $this->photo = Storage::url($filename); // get the file url for saving to your database
    }
}

$fileable

这个属性是必需的。如果你没有实现它,你的上传文件将不会工作。所以请将此实现到你的组件中。

updatedFoo($value, $old_value)

更新方法与 livewire 生命周期钩子相同。但在 livewire 中只有一个 $value,在这个方法中我添加了 $old_value。

视图实现

在你的 blade 文件中,你可以实现如下示例

<div>
  @isset($photo)
  
  <img src="{{ $photo }}">
  
  @endisset
  
  Upload Photo
  <input type="file" wire:withfile="photo">

</div>

或者,如果你想在上传文件之前调整图像的大小,以下是一个示例

<div>
  @isset($photo)
  
  <img src="{{ $photo }}">
  
  @endisset
  
  Upload Photo
  <input type="file" wire:withfile="photo" with-resize-if-image with-max-width="1080" with-max-height="1080">

</div>

或者,如果你想同时调整宽度和高度,以下是一个示例

<div>
  @isset($photo)
  
  <img src="{{ $photo }}">
  
  @endisset
  
  Upload Photo
  <input type="file" wire:withfile="photo" with-resize-if-image with-max-both="1080">

</div>

wire:withfile

使用这个属性就像使用 wire:model 一样,但它与 wire:model 不同。所以,所有在 wire:model 中实现的都不能在 wire:withfile 中实现。

with-resize-if-image

如果你上传的是图像,这将调整你的文件大小。在文件图像发送到组件之前,图像将被调整大小。

with-max-both

这将添加宽度和高度的极限。例如,如果高度大于宽度,则高度将被设置为最大值,而宽度将自动调整。

with-max-width, with-max-height

如果你想调整图像的宽度或高度的最大值,请使用此选项。