Laravel combines with Wang Editor 3 rich text editor to publish articles and upload multiple pictures

Posted by lordphilippe on Wed, 31 Jul 2019 14:02:15 +0200

Write in front
Define routing

Route::post('article/image/upload', 'ArticleController@imageUpload');

(2) Modify the configuration file config/filesystems.php, the other defaults will be fine.

//    'default' => env('FILESYSTEM_DRIVER', 'local'),
    'default' => env('FILESYSTEM_DRIVER', 'public'),

(3) Uploaded pictures can not access directories other than public, so to set up a soft link to upload files, the console executes the following commands.

php artisan storage:link

Official Document Address

1. Introduce the resource file first. The official document above has already existed. Let's put the HTML code first instead of repeating it here.

html code, head part of csrf_token, the page wrapped with form-group just for style, can also be achieved through margin, etc.

If the editor is placed in the form, errors such as "Uncaught TypeError: Cannot read property'type'of undefined" and "Assertion failed: Input argument is not an HTML Input Element" will occur.

    <meta name="csrf-token" content="{{csrf_token()}}">
@section('main')
    <div class="col-md-8 col-md-offset-2" style="margin-top: 20px;">
        
        <div class="form-group" id="title">
            <label>Title</label>
            <input name="title" type="text" class="form-control" placeholder="Here is the title.">
        </div>

        <div class="form-group">
            <label>content</label>
            <div id="editor">

            </div>
        </div>

        <button type="button" class="btn btn-default pull-right" onclick="releaseArticle()">Submission</button>

    </div>
@endsection

2. JS Code

<script type="text/javascript">
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        var E = window.wangEditor
        var editor = new E('#editor')

        // Configure the server-side address
        editor.customConfig.uploadImgServer = "{{url('article/image/upload')}}";

        // Set the name value of the file
        editor.customConfig.uploadFileName = 'wangEditorImage[]';

        //Setting headers
        editor.customConfig.uploadImgHeaders = {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        };

        // Limit image size to 3M
        editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024

        // Limit uploading up to five pictures at a time
        editor.customConfig.uploadImgMaxLength = 5

        //Custom Processing
        editor.customConfig.uploadImgHooks = {
            success: function (xhr, editor, result) {
                console.log("Upload Success");
            },
            fail: function (xhr, editor, result) {
                console.log("Upload failure,As a result of" + result);
            },
            error: function (xhr, editor) {
                console.log("Upload error");
            },
            timeout: function (xhr, editor) {
                console.log("Upload timeout");
            },
            // If the server does not return the format {errno:0, data: [...]}, you can use this configuration
            // However, the server must return a JSON format string!!! Otherwise, it will make a mistake.
            customInsert: function (insertImg, result, editor) {
                // insertImg is a function for inserting pictures, editor is an editor object, and result is the result returned by the server.
                for (let i = 0; i < result.length; i++) {
                    let url = result[i]
                    insertImg(url)
                }
            }
        };

        editor.create()
		//Publish articles
        function releaseArticle() {
            let title = $("input[name=title]").val();
            let article = editor.txt.html();

            $.ajax({
                url: " {{ url('article/add') }}",
                method: 'post',
                dataType: 'json',
                data: {
                    'title': title,
                    'article': article
                },

                success: function (data) {
                    if (data.error != 0) {
                        addErrorTips(data);
                        return;
                    }
                    window.location.href = "/index";
                }, error: function (data) {
                    addErrorTips(JSON.parse(data.responseText))
                }

            });
        }

        // Add error message dynamically on the page
        function addErrorTips(data) {
            str = '<div class="alert alert-danger" role="alert">';
            str += '<li>' + data.message + '</li>';
            str += '</div>';
            $(".alert").remove();
            $("#title").before(str);
        }
    </script>

3. Background code

//Publish articles
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {

            $data = $request->all();
            $data['uid'] = $this->getCurrentUid();

            if (Article::create($data)) {
                return json_encode(array('error' => '0'));
            } else {
                return json_encode(array('message' => 'Failure to publish articles'));
            }
        } else {
            return view('article/add');
        }
    }
//Upload pictures
    public function imageUpload(Request $request)
    {
        $images = $request->file('wangEditorImage');
        if ($images != null && count($images) > 0) {
            $url = array();
            foreach ($images as $key => $val) {
                $url[] = asset('storage/' . $val->storePublicly(md5(time())));
            }
        }

        return json_encode($url);
    }

4. Page effect

Topics: JSON PHP Javascript