Laravel admin from entry to discard (2. ueditor implements image upload and upload restrictions)

1, Install ueditor

Find the ueditor through the official extension https://laravel-admin.org/extensions, install it according to the document, and perform basic configuration operations. The rest has nothing to do with the document (no objection)

 

Here is the upgrade configuration

2, Editor toolbar configuration

Configure according to the file vendor\codingyu\laravel-ueditor\src\config\ueditor.php

3, Picture upload

Modify the upload in config/admin.php to the following

// Disk in `config/filesystem.php`.
        'disk' => 'admin',

        // Image and file upload path under the disk above.
        'directory' => [
            'image' => 'images',
            'file'  => 'files',
        ],


        'hash_filename' => true,

        /* For the configuration related to front and back end communication, only multiline mode is allowed for comments */
        /* Upload picture configuration item */
        'imageActionName' => 'upload-image', /* The name of the action to upload the picture */
//        'imagefieldname' = > upfile ', / * submitted picture form name*/
        'imageFieldName' => '{rand:15}', /* Submitted picture form name */
        'imageMaxSize' => 2 * 1024 * 1024, /* Upload size limit, unit B */
        'imageAllowFiles' => ['.png', '.jpg', '.jpeg', '.gif', '.bmp'], /* Upload image format display */
        'imageCompressEnable' => true, /* Whether to compress pictures? true by default */
        'imageCompressBorder' => 121, /* Picture compression maximum edge limit */
        'imageInsertAlign' => 'none', /* Inserted picture float */
        'imageUrlPrefix' => '', /* Picture access path prefix */
        'imagePathFormat' => '/uploads/image/{yyyy}{mm}/', /* Upload the save path. You can customize the save path and file name format */
        'imageWidth' => 121, /* Upload image width */
        'imageHeight' => 75, /* Upload image high */

        /* {filename} It will be replaced with the original file name. Please pay attention to the problem of Chinese scrambling when configuring this item */
        /* {rand:6} It will be replaced by a random number, and the following number is the number of random numbers */
        /* {time} Will be replaced with a timestamp */
        /* {yyyy} Will be replaced with four digit year */
        /* {yy} Will be replaced by two years */
        /* {mm} Will be replaced by two months */
        /* {dd} Will be replaced with two dates */
        /* {hh} Will be replaced by two hours */
        /* {ii} Will be replaced by two minutes */
        /* {ss} Will be replaced with two bit seconds */
        /* Illegal character \ = > *? "< >| */
        /* Please see the online document = > Fex. Baidu. COM / assets / ා use format ﹐ upload ﹐ filename */

        /* Doodle picture upload configuration item */
        'scrawlActionName' => 'upload-scrawl', /* Name of action to upload graffiti */
        'scrawlFieldName' => 'upfile', /* Submitted picture form name */
        'scrawlPathFormat' => '/uploads/image/{yyyy}{mm}/', /* Upload the save path. You can customize the save path and file name format */
        'scrawlMaxSize' => 2048000, /* Upload size limit, unit B */
        'scrawlUrlPrefix' => '', /* Picture access path prefix */
        'scrawlInsertAlign' => 'none',

        /* Screenshot tool upload */
        'snapscreenActionName' => 'upload-image', /* Name of action to upload screenshot */
        'snapscreenPathFormat' => '/uploads/image/{yyyy}{mm}/', /* Upload the save path. You can customize the save path and file name format */
        'snapscreenUrlPrefix' => '', /* Picture access path prefix */
        'snapscreenInsertAlign' => 'none', /* Inserted picture float */

        /* Grab remote picture configuration */
//                'catcherLocalDomain' => ['127.0.0.1', 'localhost', 'img.baidu.com'],
//                'catcheractionname' = > 'catch image', / * the name of the action to grab the remote picture*/
//                'catcherfieldname' = > source ', / * submitted picture list form name*/
//                'catcherpathformat' = > '/ uploads / image / {yyyy} / {mm} / {DD} /', / * upload save path. You can customize save path and file name format*/
//                'catcherurlprefix' = [1jeemaa1] '', / * image access path prefix*/
//                'catchermaxsize' = > 2048000, / * upload size limit, unit B*/
//                'catcherallowfiles' = > ['. PNG ','. JPG ','. JPEG ','. GIF ','. BMP '], / * grab image format display*/

        /* Upload video configuration */
//                'videoactionname' = > upload video '/ * the name of the action to upload the video*/
//                'videofieldname' = > upfile ', / * submitted video form name*/
//                'videopathformat' = > '/ uploads / video / {yyyy} / {mm} / {DD} /', / * upload save path. You can customize save path and file name format*/
//                'videourlprefix' = [1jeemaa1] '', / * video access path prefix*/
//                'videomaxsize' = > 102400000, / * upload size limit, unit B, default 100MB*/
//                'videoAllowFiles' => [
//                    '.flv', '.swf', '.mkv', '.avi', '.rm', '.rmvb', '.mpeg', '.mpg',
//                    '. Ogg', 'OGV', 'mov', 'WMV', 'MP4', 'WebM', 'MP3', 'wav', 'mid',], / * upload video format display*/

        /* Upload file configuration */
        'fileActionName' => 'upload-file', /* controller The name of the action to upload the video */
        'fileFieldName' => 'upfile', /* Submitted file form name */
        'filePathFormat' => '/uploads/file/{yyyy}{mm}/', /* Upload the save path. You can customize the save path and file name format */
        'fileUrlPrefix' => '', /* File access path prefix */
        'fileMaxSize' => 51200000, /* Upload size limit, unit B, default 50MB */
        'fileAllowFiles' => [
            '.png', '.jpg', '.jpeg', '.gif', '.bmp',
//                    '.flv', '.swf', '.mkv', '.avi', '.rm', '.rmvb', '.mpeg', '.mpg',
//                    '.ogg', '.ogv', '.mov', '.wmv', '.mp4', '.webm', '.mp3', '.wav', '.mid',
//                    '.rar', '.zip', '.tar', '.gz', '.7z', '.bz2', '.cab', '.iso',
            '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf', '.txt', '.md', '.xml',
        ], /* Upload file format display */

        /* List pictures in the specified directory */
        'imageManagerActionName' => 'list-image', /* Name of the action to perform picture management */
        'imageManagerListPath' => '/uploads/image/', /* Specify the directory to list pictures in */
        'imageManagerListSize' => 20, /* Number of files listed at a time */
        'imageManagerUrlPrefix' => '', /* Picture access path prefix */
        'imageManagerInsertAlign' => 'none', /* Inserted picture float */
        'imageManagerAllowFiles' => ['.png', '.jpg', '.jpeg', '.gif', '.bmp'], /* File types listed */

        /* List files in the specified directory */
        'fileManagerActionName' => 'list-file', /* Name of action to perform file management */
        'fileManagerListPath' => '/uploads/file/', /* Specify the directory to list files in */
        'fileManagerUrlPrefix' => '', /* File access path prefix */
        'fileManagerListSize' => 20, /* Number of files listed at a time */
        'fileManagerAllowFiles' => [
            '.png', '.jpg', '.jpeg', '.gif', '.bmp',
//                    '.flv', '.swf', '.mkv', '.avi', '.rm', '.rmvb', '.mpeg', '.mpg',
//                    '.ogg', '.ogv', '.mov', '.wmv', '.mp4', '.webm', '.mp3', '.wav', '.mid',
//                    '.rar', '.zip', '.tar', '.gz', '.7z', '.bz2', '.cab', '.iso',
            '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf', '.txt', '.md', '.xml',
        ], /* File types listed */

 

Add the intervention/image extension to realize the size limit of the uploaded image. If it is larger than the set size, it will be cropped

Installation: composer require intervention/image,

Publish configuration: PHP artican vendor: publish -- provider = "interaction \ image \ imageserviceproviderlaraverecent"

The encapsulation method is as follows:

 public function reduceSize($file_path, $max_width)
    {
        // Instantiate first, and pass parameter is the disk physical path of the file
        $image = \Image::make($file_path);

        // Resizing
        $image->resize($max_width, null, function ($constraint) {

            // Set the width to be $max? Width, height to be scaled equally
            $constraint->aspectRatio();

            // Prevent picture size from getting larger when cutting
            $constraint->upsize();
        });

        // Save the picture after modification
        $image->save();

Error reporting: call to undefined method interaction \ image \ image:: make() solution

Open config/app.php, find the providers array, and add

Intervention\Image\ImageServiceProvider::class

 

Same as aliaes array in the file:

'Image' => Intervention\Image\Facades\Image::class

 

report errors:
Call to undefined method Intervention\Image\Image::make()

Use interaction \ image \ image;

Replace with

use Intervention\Image\ImageManagerStatic as Image;

 

The following is to modify the background file of \ vendor \ codingyu \ laravel ueditor \ SRC \ storagemanager.php

<?php

/*
 * This file is part of the overtrue/laravel-ueditor.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Codingyu\LaravelUEditor;

use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Codingyu\LaravelUEditor\Events\Catched;
use Codingyu\LaravelUEditor\Events\Uploaded;
use Codingyu\LaravelUEditor\Events\Uploading;
use Illuminate\Contracts\Filesystem\Filesystem;
//use Intervention\Image\Image;
use Intervention\Image\ImageManagerStatic as Image;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * Class StorageManager.
 */
class StorageManager
{
    use UrlResolverTrait;

    /**
     * @var \Illuminate\Contracts\Filesystem\Filesystem
     */
    protected $disk;

    /**
     * Constructor.
     *
     * @param \Illuminate\Contracts\Filesystem\Filesystem $disk
     */
    public function __construct(Filesystem $disk)
    {
        $this->disk = $disk;
    }

    /**
     * Upload a file.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload(Request $request)
    {
        $config = $this->getUploadConfig($request->get('action'));
//        $config = ['action','field_name','max_size','allow_files','path_format'];

        if (!$request->hasFile($config['field_name'])) {
            return $this->error('UPLOAD_ERR_NO_FILE');
        }

        $file = $request->file($config['field_name']);

        if ($error = $this->fileHasError($file, $config)) {
            return $this->error($error);
        }

        $filename = $this->getFilename($file, $config);

        if ($this->eventSupport()) {
            $modifiedFilename = event(new Uploading($file, $filename, $config), [], true);
            $filename = !is_null($modifiedFilename) ? $modifiedFilename : $filename;
        }

        $this->store($file, $filename);

        // Crop image to specified size
        $adminConf = config('admin.upload');
        $imgData = getimagesize($this->getUrl($filename));
        if($imgData[0] > $adminConf['imageWidth'] OR $imgData[1] > $adminConf['imageHeight']){
            $this->reduceSize(public_path('admin').$filename, $adminConf['imageWidth']);
        }
        $imgName = substr($filename,strripos($filename,'/')+1);

//        $response = [
//            'state' => 'SUCCESS',
//            'url' => $this->getUrl($filename),
//            'title' => $filename,
//            'original' => $file->getClientOriginalName(),
//            'type' => $file->getExtension(),
//            'size' => $file->getSize(),
//        ];

        $response = [
            'state' => 'SUCCESS',
            'url' => $this->getUrl($filename),
            'title' => $imgName,
            'original' => $imgName,
            'type' => $file->getExtension(),
            'size' => $file->getSize(),
        ];

        if ($this->eventSupport()) {
            event(new Uploaded($file, $response));
        }

        //Delete source file
//        unlink($filename);

        return response()->json($response);
    }

    /**
     * Fetch a file.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function fetch(Request $request)
    {
        $config = $this->getUploadConfig($request->get('action'));
        $urls = $request->get($config['field_name']);
        if (count($urls) === 0) {
            return $this->error('UPLOAD_ERR_NO_FILE');
        }
        $urls = array_unique($urls);

        $list = array();
        foreach ($urls as $key => $url) {
            $img = $this->download($url, $config);
            $item = [];
            if ($img['state'] === 'SUCCESS') {
                $file = $img['file'];
                $filename = $img['filename'];
                $this->storeContent($file, $filename);
                if ($this->eventSupport()) {
                    unset($img['file']);
                    event(new Catched($img));
                }
            }
            unset($img['file']);
            array_push($list, $img);
        }

        $response = [
            'state' => count($list) ? 'SUCCESS' : 'ERROR',
            'list' => $list
        ];

        return response()->json($response);
    }

    /**
     * Download a file.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return Array $info
     */
    private function download($url, $config)
    {
        if (strpos($url, 'http') !== 0) {
            return $this->error('ERROR_HTTP_LINK');
        }
        $pathRes = parse_url($url);
        $img = new \SplFileInfo($pathRes['path']);
        $original = $img->getFilename();
        $ext = $img->getExtension();
        $title = md5($url) . '.' . $ext;
        $filename = $this->formatPath($config['path_format'], $title);
        $info = [
            'state' => 'SUCCESS',
            'url' => $this->getUrl($filename),
            'title' => $title,
            'original' => $original,
            'source' => $url,
            'size' => 0,
            'file' => '',
            'filename' => $filename,
        ];

        $context = stream_context_create(
            array('http' => array(
                'follow_location' => false, // don't follow redirects
            ))
        );
        $file = fopen($url, 'r', false, $context);
        if ($file === false) {
            $info['state'] = 'ERROR';
            return $info;
        }
        $content = stream_get_contents($file);
        fclose($file);

        $info['file'] = $content;
        $info['siez'] = strlen($content);
        return $info;
    }

    /**
     * @return bool
     */
    public function eventSupport()
    {
        return trait_exists('Illuminate\Foundation\Events\Dispatchable');
    }

    /**
     * List all files of dir.
     *
     * @param string $path
     * @param int    $start
     * @param int    $size
     * @param array  $allowFiles
     *
     * @return Response
     */
    public function listFiles($path, $start, $size = 20, array $allowFiles = [])
    {
        $allFiles = $this->disk->listContents($path, true);
        $files = $this->paginateFiles($allFiles, $start, $size);

        return [
            'state' => empty($files) ? 'EMPTY' : 'SUCCESS',
            'list' => $files,
            'start' => $start,
            'total' => count($allFiles),
        ];
    }

    /**
     * Split results.
     *
     * @param array $files
     * @param int   $start
     * @param int   $size
     *
     * @return array
     */
    protected function paginateFiles(array $files, $start = 0, $size = 50)
    {
        return collect($files)->where('type', 'file')->splice($start)->take($size)->map(function ($file) {
            return [
                'url' => $this->getUrl($file['path']),
                'mtime' => $file['timestamp'],
            ];
        })->all();
    }

    /**
     * Store file.
     *
     * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file
     * @param string                                              $filename
     *
     * @return mixed
     */
    protected function store(UploadedFile $file, $filename)
    {
        return $this->disk->put($filename, fopen($file->getRealPath(), 'r+'));
    }

    /**
     * Store file from content.
     *
     * @param string
     * @param string                                              $filename
     *
     * @return mixed
     */
    protected function storeContent($content, $filename)
    {
        return $this->disk->put($filename, $content);
    }

    /**
     * Validate the input file.
     *
     * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file
     * @param array                                               $config
     *
     * @return bool|string
     */
    protected function fileHasError(UploadedFile $file, array $config)
    {
        $error = false;

        if (!$file->isValid()) {
            $error = $file->getError();
        } elseif ($file->getSize() > $config['max_size']) {
            $error = 'upload.ERROR_SIZE_EXCEED';
        } elseif (
            !empty($config['allow_files']) &&
            !in_array('.' . $file->getClientOriginalExtension(), $config['allow_files'])
        ) {
            $error = 'upload.ERROR_TYPE_NOT_ALLOWED';
        }

        return $error;
    }

    /**
     * Get the new filename of file.
     *
     * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file
     * @param array                                               $config
     *
     * @return string
     */
    protected function getFilename(UploadedFile $file, array $config)
    {
        $ext = '.' . $file->getClientOriginalExtension();

//        $filename = config('ueditor.hash_filename') ? md5($file->getFilename()) . $ext : $file->getClientOriginalName();
        $filename = randStr($len=20, $ul=2, $letter=1).$ext;

        return $this->formatPath($config['path_format'], $filename);
    }

    /**
     * Get configuration of current action.
     *
     * @param string $action
     *
     * @return array
     */
    protected function getUploadConfig($action)
    {
//        $upload = config('ueditor.upload');
        $upload = config('admin.upload');
//        prt($upload);
        $prefixes = [
            'image', 'scrawl', 'snapscreen', 'catcher', 'video', 'file',
            'imageManager', 'fileManager',
        ];

        $config = [];

        foreach ($prefixes as $prefix) {
            if ($action == $upload[$prefix . 'ActionName']) {
                $config = [
                    'action' => Arr::get($upload, $prefix . 'ActionName'),
                    'field_name' => Arr::get($upload, $prefix . 'FieldName'),
                    'max_size' => Arr::get($upload, $prefix . 'MaxSize'),
                    'allow_files' => Arr::get($upload, $prefix . 'AllowFiles', []),
                    'path_format' => Arr::get($upload, $prefix . 'PathFormat'),
                ];

                break;
            }
        }

        return $config;
    }

    /**
     * Make error response.
     *
     * @param $message
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function error($message)
    {
        return response()->json(['state' => trans("ueditor::upload.{$message}")]);
    }

    /**
     * Format the storage path.
     *
     * @param string $path
     * @param string $filename
     *
     * @return mixed
     */
    protected function formatPath($path, $filename)
    {
        $replacement = array_merge(explode('-', date('Y-y-m-d-H-i-s')), [$filename, time()]);
        $placeholders = ['{yyyy}', '{yy}', '{mm}', '{dd}', '{hh}', '{ii}', '{ss}', '{filename}', '{time}'];
        $path = str_replace($placeholders, $replacement, $path);

        //Replace random string
        if (preg_match('/\{rand\:([\d]*)\}/i', $path, $matches)) {
            $length = min($matches[1], strlen(PHP_INT_MAX));
            $path = preg_replace('/\{rand\:[\d]*\}/i', str_pad(mt_rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT), $path);
        }

        if (!Str::contains($path, $filename)) {
            $path = Str::finish($path, '/') . $filename;
        }

        return $path;
    }

    /**
     * @param $file_path
     * @param $max_width
     */
    public function reduceSize($file_path, $max_width = null, $max_hight = null){
        // Instantiate first, and pass parameter is the disk physical path of the file
        $image = Image::make($file_path);

        // Resizing
        $image->resize($max_width, $max_hight, function ($constraint) {

            // Set the width to be $max? Width, height to be scaled equally
            $constraint->aspectRatio();

            // Prevent picture size from getting larger when cutting
            $constraint->upsize();
        });

        // Save the picture after modification
        $image->save();
    }
}



/****************************************
 *  @Explain:  Random survival string
 *  @Remarks:
 *  @Param:       $len:Length of survival string, $ul: difference between case, 1: mixed case, 2: lowercase, 3: uppercase, $letter: character nature, 1: mixed number and character, 2: pure character, 3: pure number
 *  @Return:
 ****************************************/
function randStr($len=0, $ul=1, $letter=1){
    $len            = (int)$len;
    if($len < 1){return '';}
    $strArr             = array('1','2','3','4','5','6','7','8','9','0','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
    if($letter == 3){
        $strArr          = array_slice($strArr, 0, 10);
    }elseif ($letter == 2){
        $strArr          = array_slice($strArr, 10);
    }
    $max            = count($strArr) - 1;
    $result             = '';
    for ($i=0;$i<$len;$i++){
        $key         = rand(0, $max);
        $result          .= $strArr[$key];
    }
    if($ul == 2){
        $result    = strtolower($result);
    }elseif ($ul == 3){
        $result    = strtoupper($result);
    }
    return $result;
}

 

Slowly updating

Tags: Programming PHP Laravel JSON xml

Posted on Wed, 22 Apr 2020 08:19:19 -0700 by rich11