yektadg/medialibrary

此包的最新版本(2.1)没有提供许可证信息。

用于处理项目媒体文件的简单库

2.1 2023-12-19 13:57 UTC

This package is auto-updated.

Last update: 2024-09-19 15:42:51 UTC


README

MediaLibrary 是一个用于在 Laravel 项目中处理图像的 Laravel 库。您可以上传图像,修改它们的 alt 属性,将它们分类到文件夹中等等。它还将您的图像压缩成四种不同的大小,并保留原始大小,因此您可以根据用户屏幕或使用懒加载来访问它们。

Packagist Version License: GPL v3

截图

laravel-media-library

安装

您可以通过 composer 安装此包

 composer require yektadg/medialibrary

安装完成后,您应该发布提供的资产以创建必要的迁移和配置文件。

 php artisan vendor:publish --provider="YektaDG\Medialibrary\Providers\MediaLibraryServiceProvider" 

要求

BootStrap 5

jQuery

Axios Js

使用方法

只需在您的 Laravel blade 文件的最后添加以下行,所有 JavaScript 代码之后。

<x-mediaLibrary::ml-init :id="your prefered id(withoutspace)"></x-mediaLibrary::ml-init>

如果您只想访问媒体库视图并与您自定义的视图一起使用,可以使用以下行。

<x-mediaLibrary::media-library :libraryId="your prefered id(withoutspace)"></x-mediaLibrary::media-library>

如果您想在同一页面上同时使用两者,请注意它们之间的 id 冲突。

然后您必须将 ml-button 类添加到您的 HTML 按钮中,以便打开库。

您可以使用 MediaLibrary 来处理不同的用途类型(您可以在本节下查看所有用法),因此在定义按钮时应该指定它。

定义 MediaLibrary 用于 hidden 用法的示例

<button
        useType="hidden"
        multipleSelect="true"
        useId="image-holder-1"
        class="ml-button"
        type="button">
    Upload Images
</button>
<input id="image-holder-1" type="hidden" name="image-holder" class="image-holder">

在上面的代码中,点击 上传图像 后,MediaLibrary 会弹出,选择图像后,它们将存储在具有 html id image-holder-1 的隐藏输入中。

上面的三个属性是 MediaLibrary 属性。您可以在下面的部分中查看所有 MediaLibrary 属性。

属性

MediaLibrary 在 HTML 元素(如按钮、锚点等)上使用不同的 HTML 属性来处理不同的情况。

以下列出了属性列表

注意:所有属性及其值都是大小写敏感的

功能

限制对媒体的访问

您可以通过向 Laravel 中间件添加 accessAllMedia 属性来限制对媒体的访问。

以下是如何做的示例

  1. 首先使用 Laravel 命令 php artisan make:middleware CheckAccessMedia 创建一个中间件
  2. 在项目的 Http 文件夹中的 kernel.php 文件中注册您的中间件,在配置文件夹中的 medialibray.php 文件中的 $routeMiddleware 数组中添加您的中间件别名 'CheckMediaAccess' => CheckMediaAccess::class
  3. 然后,在项目的配置文件夹中的 medialibray.php 文件中的 middleware 数组中添加您的中间件别名,在这种情况下是 'CheckMediaAccess'
  4. 编辑您新创建的中间件,并添加您的条件,例如
public function handle(Request $request, Closure $next)
   {
       $user = auth()->user();
       $condition = false;
       if ($user && $user->id == 1) {
           $condition = true;
       }
       $request->merge(['accessAllMedia' => $condition]);

       return $next($request);
   }

在上面的示例中,ID 为 1 的用户可以访问所有上传的媒体,但所有其他用户只能访问他们的媒体。

懒加载

MediaLibrary 生成四种不同大小的图像,您可以使用它们进行懒加载。以下代码根据用户屏幕大小加载图像

/**
 * changes the image tag src based on windwos
 */
$(document).ready(() => {
    let images = [];
    let i = 0;
    $('.resizing').each(function () {
        const sizes = [1280, 1500];
        let src = $(this).attr('originalSrc');
        let name = src.slice(0, src.lastIndexOf('.'))
        let size = getClosest(sizes, $(window).width());
        let ext = src.substring(src.lastIndexOf(".") + 1);
        let path = name + `-${size}x-${ext}`;

        images.push({
            'id': ++i,
            'element': this,
            'url': path,
        })
    })
    if (images.length > 0) {
        imageExist(images)
    }
})


/**
 * check if image exists then put it in src else replace it with original Image
 */
function imageExist(images) {
    const result = images.reduce((obj, cur) => ({...obj, [cur.id]: cur}), {})   //converting to map
    axios.post(imageExistRoute, {
        'images': images
    }).then(res => {
        res.data.forEach(el => {
            let element = $(result[el['id']]['element']);
            if (el['element'] == true) {
                element.attr('src', el['url'])       //  setting the new src
            } else {
                element.attr('src', element.attr('originalSrc'))
            }
        })
    }).catch();
}

/**
 * returns the closest number to the window size
 * @param arr
 * @param target
 * @returns {*}
 */
function getClosest(arr, target) {
    if (arr == null) {
        return
    }
    return arr.reduce((prev, current) => Math.abs(current - target) < Math.abs(prev - target) ? current : prev);
}

注意:您需要在上述代码之前定义 imageExistRoute

const imageExistRoute = '{{route('medialibrary.image-exists')}}';

然后,您可以通过向 HTML 图像标签添加 resizing 类和 originalSrc 属性来使用懒加载。

 <img class="resizing" src="address to your default image"
      originalSrc="address to your real image" alt="">

注意:默认图像应该具有较小的磁盘大小,并且对所有页面都是常量图像

语言

您可以通过编辑 toast.blade.php 来更改在 resources/views/vendor/yektadg/medialibrary 中的 toast 标题。

要更改 toast 消息,请编辑 mlLang.js,它在 public/vendor/yektadg/medialibrary 中。