Laravel Project using Markdown Editor and picture paste upload seven Qiniu

Source: Internet
Author: User

This article is reproduced, original: HTTP://WWW.CHAIRIS.CN/BLOG/ARTICLE/15

Markdown

Markdown is a markup language that can be written using an ordinary text editor, which can have a certain format for normal text content with simple markup syntax.
This time we choose the editor is: EDITOR.MD, the official website also has a very detailed introduction. Download the installation from the official website

Download the content, there are many demos can learn from.
In the downloaded package, remove some extraneous content, keep only what we need, and add it to the project's public directory, such as the contents of the Red box:

Used in projects

When you use EDITOR.MD to edit content in your project, first add the corresponding reference in the blade template, and the CSS reference is as follows:

<link rel= "stylesheet" href= "{{asset (' Editormd/editormd.min.css ')}}" >

JS is quoted as follows:

<script src= "{{asset (' Editormd/editormd.min.js ')}}" Type= "Text/javascript" ></script>

Then add the following code to the HTML as the editor area.

<div id= "Myeditormd" >    <textarea style= "Display:none;" ></textarea></div>

  

Finally, add the JS code and load the EDITOR.MD:

<script type= "Text/javascript" >        var testeditor;        $ (function () {            testeditor = EDITORMD ("Myeditormd", {                width: "100%",                height:600,                syncscrolling: " Single ",                tasklist:true,                tocm:true,                path:" {{asset ('/editormd/lib/')}} "+"/",                tex:true,                FlowChart       : True,                sequencediagram:true,                savehtmltotextarea:true,                imageuploadurl: "php/ Upload.php ",            });        }); </script>

  

Relevant parameter meaning:

Savehtmltotextarea: Save HTML to Textarea
Tex: Scientific Formula Tex language support, default off
FlowChart: Flowchart support, default off
Sequencediagram: Time series/sequence diagram support, default off
Toolbar: toolbar, open by default
Watch: Live preview, open by default

This allows the editor to be fully loaded. Effects such as:

There are some of the more important JS methods.

Testeditor.gotoline (90);//jump To Line 90th testeditor.show ();//display Editor testeditor.hide;//Hide editor Testeditor.getmarkdown ();// Get Markdown Code testeditor.gethtml ();//get markdown parsed HTML code testeditor.watch ();//Turn on real-time preview testeditor.unwatch ();// Close Live preview testeditor.previewing ();//preview Testeditor.fullscreen ();//Full Screen testeditor.showtoolbar ();// Show toolbar Testeditor.hidetoolbar ();//Hide Toolbar

When you finish editing content in the editor, the markdown tag is typically saved. But how to parse the saved markdown tag.

Markdown Parsing

Add the following references:

CSS references <link rel= "stylesheet" href= "{{asset (' Editormd/editormd.min.css ')}}" >//js reference <script src= "{{Asset (' Editormd/editormd.min.js ')}} "Type=" Text/javascript "></script><script src=" {{Asset (' editormd/lib/ Marked.min.js ')}} "></script><script src=" {{asset (' Editormd/lib/prettify.min.js ')}} "></script ><script src= "{{asset (' Editormd/lib/raphael.min.js ')}}" ></script><script src= "{{Asset (' Editormd/lib/underscore.min.js ')}} "></script><script src=" {{Asset (' editormd/lib/ Sequence-diagram.min.js ')}} "></script><script src=" {{asset (' Editormd/lib/flowchart.min.js ')}} "> </script><script src= "{{asset (' Editormd/lib/jquery.flowchart.min.js ')}}" ></script>

Then add the parsed area to the HTML

<div id= "Show_editor" >    <textarea style= "Display:none" >{{$article->content}}</textarea> </div>

where {{$article->content}} is a saved markdown tag read in the database.
Finally add the response to the JS code, it can be perfectly parsed.

<script type= "Text/javascript" >    $ (function () {        var testeditormdview;        Testeditormdview = editormd.markdowntohtml ("Show_editor", {            htmldecode      : "Style,script,iframe",  //You Can filter tags decode            emoji           : True,            taskList        : True,            Tex             : True,  //default not resolved            FlowChart       : True,  //default does not resolve            sequencediagram:true,  //default not resolved        })    ; </script>

The parsed effect is as follows:

Image paste Upload

First analyze the implementation steps:

  1. QQ after pasting in the editor, there will certainly be a paste event, that is, the Paste event
  2. One-time compression of a picture on the front end in an event callback function
  3. Front-end compression is mostly using canvas, the return is Base64, here I use a localresizeimg.js plug-in
  4. The generated good base64 to the background, the background can be a picture of the second compression, but it does not feel necessary
  5. Backstage first get seven Qiniu Uptoken, that is, an uploaded voucher, and then perform the upload function provided by the seven KN SDK

    Paste Events

    After that, right-pasting or ctrl-V in the Rich Text editor triggers this event, which has a Clipboarddata property. We need to use JS code to listen to the paste event and get the Clipboarddata property, the code is as follows:

    1. function paste (event) {var clipboarddata = Event.clipboarddata;         var items, item, types;             if (clipboarddata) {items = Clipboarddata.items;             if (!items) {return; }//data type saved in Clipboard types = Clipboarddata.types | |             []; for (var i = 0; i < types.length; i++) {if (types[i] = = = ' Files ') {item = Items[i                     ];                 Break }}//Determine if the image data if (item && item.kind = = = ' file ' && item.type.match (/ ^image\//i) {//Read the picture var file = Item.getasfile (), reader = new                 FileReader ();                 Reader.readasdataurl (file); Reader.onload = function () {///front-end compression Lrz (Reader.result, {width:1080}). Then (functi                       On (res) {$.ajax ({      URL: "{{asset (' php-sdk/myapis/uploadimagetoqiliu.php ')}}", type: ' Post ', Data: {"image": Res.base64, "name": New Date (). GetTime () + ". png"}, ContentType: ' Application/x-www-form-urle Ncoded;charest=utf-8 ', success:function (data) {var Imagenam                                 E                                 try {imageName = json.parse (data). Key;                                 } catch (e) {alert (e.tostring); } var qiniuurl = '!                                 [] (http://opgmvuzyu.bkt.clouddn.com/' + imageName + ') ';                             Testeditor.insertvalue (Qiniuurl);              }                         })                     });   }}}} document.addeventlistener (' Paste ', function (event) {paste (event); })

        


    Front-End compression

    Front-end compression is using the Localresizeimg.js plugin.
    Compatible with IE10 above, so also have to do an IE version of Judgment, and then see if they need to use dry this plugin, I do not write IE judgment.
    Using the method is also very simple, the Lrz method accepts a file path or Base64 picture, you can set a compression width of the object, lower than the width of the picture will not be compressed, larger than the width of the compression, and then in the method to obtain the compressed picture:
    This plugin should be introduced first, can be introduced using SRC, and also support AMD or CMD modularity

      1. <script src= "{{asset (' Js/lrz.bundle.js ')}}" Type= "Text/javascript" ></script>

    Start using:

      1. Image is the picture Lrz (image, {width:1080}) that was obtained after the paste event. Then (function (res) {var base64 = Res.base64;}
    Seven Qiniu SDK

    Seven Qiniu registration seems to send 10G cloud storage, need to register, first download the seven Qiniu SDK, I use PHP, address https://developer.qiniu.com/kodo/sdk/php
    It's also easy to configure this uploaded file. Unzip the downloaded package, delete the unused file, and drag it to the project:

    uploadimagetoqiliu.php file is self-added, the code is as follows:

      1. <?phprequire_once __dir__. ‘/.. /autoload.php '; use qiniu\auth;//introduce upload class use Qiniu\storage\uploadmanager; $accessKey = ' your AccessKey '; $secretKey = ' Your secretkey ';//Initialize the right-of-signing object. $auth = new Auth ($accessKey, $secretKey); $bucket = "Space name"; $upToken = $auth->uploadtoken ($bucket);//Initialize UploadManager object and upload the file. $UPLOADMGR = new UploadManager (); $key = $_post[' name ']; $filePath = $_post[' image '];list ($ret, $err) = $uploadMgr Putfile ($upToken, $key, $filePath), if ($err!== null) {echo json_encode ($err),} else {echo json_encode ($ret);}

    AccessKey and Secretkey register to see that bucket is the cloud storage space name.
    Next is the foreground passes the picture and the picture name to the backstage, the picture name I directly uses the new Date (). GetTime ().

      1. $.ajax ({url: "{{asset (' php-sdk/myapis/uploadimagetoqiliu.php ')}}", type: ' Post ', data: {     "image": Res.base64,     "name": New Date (). GetTime () + ". png"}, ContentType: ' Application/x-www-form-urlencoded;charest=utf-8 ', success: function (data) {     var imageName;     try {         imageName = json.parse (data). Key;     } catch (e) {         alert (e.tostring);     }     var qiniuurl = '! [] (http://opgmvuzyu.bkt.clouddn.com/' + imageName + ') ';    Testeditor.insertvalue (Qiniuurl); }})

    Testeditor is an object instance of the Markdown editor that I use, Testeditor.insertvalue (Qiniuurl), which is to insert a formatted MARKDOWN statement at the cursor.
    The entire front-end code is as follows:

    1. <script type= "Text/javascript" > Function paste (event) {var clipboarddata = Event.clipboarddata;         var items, item, types;             if (clipboarddata) {items = Clipboarddata.items;             if (!items) {return; }//data type saved in Clipboard types = Clipboarddata.types | |             []; for (var i = 0; i < types.length; i++) {if (types[i] = = = ' Files ') {item = Items[i                     ];                 Break }}//Determine if the image data if (item && item.kind = = = ' file ' && item.type.match (/ ^image\//i) {//Read the picture var file = Item.getasfile (), reader = new                 FileReader ();                 Reader.readasdataurl (file); Reader.onload = function () {///front-end compression Lrz (Reader.result, {width:1080}). Then (functi              On (RES) {           $.ajax ({url: "{{asset (' php-sdk/myapis/uploadimagetoqiliu.php ')}}",                                 Type: ' Post ', data: {"image": Res.base64,                             "Name": New Date (). GetTime () + ". png"},                                 ContentType: ' Application/x-www-form-urlencoded;charest=utf-8 ', success:function (data) {                                 var imageName;                                 try {imageName = json.parse (data). Key;                                 } catch (e) {alert (e.tostring); } var qiniuurl = '!                                 [] (http://opgmvuzyu.bkt.clouddn.com/' + imageName + ') ';                             Testeditor.insertvalue (Qiniuurl);                       }  })                     });     }}}} document.addeventlistener (' Paste ', function (event) {paste (event); }) </script>

    After pasting the picture in the editor, the effect is as follows:

Finish

Laravel Project using Markdown Editor and picture paste upload seven Qiniu

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.