Metronic-based Bootstrap development framework Experience Summary (17) -- use the summernote plug-in to edit HTML documents and insert images,
In many cases, we need to edit HTML content online and display it on pages or other terminals (such as small programs and apps). There are many plug-ins for editing HTML content, this article describes how to edit HTML documents and insert images using the Bootstrap-based summernote plug-in. This control is easy to use and has a large user base.
Summernote is a simple and flexible WYSIWYG editor. Summernote is a lightweight and flexible HTML text editor based on Bootstrap and jQuery. It has powerful API configuration functions, support for Bootstrap2.x and 3.0 in multiple languages, video and image uploads, and code highlighting.
Examples of background language versions and multi-subject support. In terms of browser compatibility, support for IE9 + and modern browsers such as Chrome, Firefox, and Safari should be good at mobile terminals, it is quite good and worth using.
This plug-in is open-source and available on the official website: plugin.
1. simple use of Summernote
Usage:
1) Load JS and CSS
<!-- include libraries(jQuery, bootstrap) --><link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet"><script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> <script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script> <!-- include summernote css/js--><link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.7/summernote.css" rel="stylesheet"><script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.7/summernote.js"></script>
In the Asp.net application based on MVC, We initialize our JS file in BundleConfig. cs, as shown below.
// Add css_metronic.Include ("~ /Content/metronic/assets/global/plugins/bootstrap-summernote/summernote.css "); js_metronic.Include ("~ /Content/metronic/assets/global/plugins/bootstrap-summernote/summernote. min. js "); js_metronic.Include ("~ /Content/metronic/assets/global/plugins/bootstrap-summernote/lang/summernote-zh-CN.min.js ");
bundles.Add(css_metronic); bundles.Add(js_metronic);
2) Compile HTML content
Add the following tag in the HTML page code.
<div id="summernote">Hello Summernote</div>
3) Initiate a call
The simple initialization code is as follows.
$(document).ready(function() { $('#summernote').summernote();});
If the definition of the control height is added, It is shown as follows.
$('#summernote').summernote({ height: 300, focus: true });
The detailed initialization interface generally includes processing Code such as internationalization of languages and image uploading, as shown below:
function initEditor() { $('#Note').summernote({ lang: 'zh-CN', // default: 'en-US' height: 600, // set editor height minHeight: null, // set minimum height of editor maxHeight: null, // set maximum height of editor focus: true, // set focus to editable area after initializing summe callbacks: { onImageUpload: function (files) { //the onImageUpload API img = sendFile(files[0]); } } });}
4) obtain the content
var markupStr = $('#summernote').summernote('code');
5) set content
The set content is similar to the get content. Add the HTML content to be written after the code.
var markupStr = 'hello world';$('#summernote').summernote('code', markupStr);
2. Use of the summernote plug-in the actual project
This section describes how to use the general summernote plug-in. In general, in addition to editing HTML content, we also need to process image uploads, to ensure that we can directly upload files to the background file system, rather than converting them into Base64 encoding on the page.
The general initialization code is as follows.
function initEditor() { $('#Note').summernote({ lang: 'zh-CN', // default: 'en-US' height: 600, // set editor height minHeight: null, // set minimum height of editor maxHeight: null, // set maximum height of editor focus: true, // set focus to editable area after initializing summe callbacks: { onImageUpload: function (files) { //the onImageUpload API img = sendFile(files[0]); } } }); }
The sendFile function is as follows. It mainly calls the attachment management module to store files.
// Submit the file to the server for processing function sendFile (file) {data = new FormData (); data. append ("file", file); // Add additional parameter data. append ("folder", 'item information'); data. append ("guid", $ ("# ID "). val (); $. ajax ({data: data, type: "POST", url: "/FileUpload/Upload", cache: false, contentType: false, processData: false, success: function (json) {var data = $. parseJSON (json); var url = data. urls [0]; $ ("# Note "). summernote ('insertimage', url, 'image name'); // the insertImage API }});}
Generally, to share and process files among multiple applications, we recommend that you use FTP, in this regard, you can refer to the additional support for FTP upload and preview in the attachment management module, FTP File Upload can use FluentFTP this component (GitHub address: https://github.com/hgupta9/FluentFTP ), this is an FTP component with a wide range of applications and powerful functions.
The background controller code for uploading attachments to the server is as follows, mainly to Build File Information, return the corresponding URL after uploading, and then you can display the image on the summernote plug-in.
/// <Summary> /// upload the attachment to the server /// </summary> /// <param name = "fileData"> Attachment Information </param> // /<param name = "guid"> attachment group GUID </param> // <param name = "folder"> specified upload directory </param> // <returns> </returns> [AcceptVerbs (HttpVerbs. post)] public ActionResult Upload (string guid, string folder) {// if you need to modify the field display, refer to the following code to process dynamic obj = new ExpandoObject (); list <string> urls = new List <string> (); var result = new CommonResult (); HttpFileCollectionBase files = HttpContext. Request. Files; if (files! = Null) {foreach (string key in files. Keys) {try {# region MyRegion HttpPostedFileBase fileData = files [key]; if (fileData! = Null) {HttpContext. request. contentEncoding = Encoding. getEncoding ("UTF-8"); HttpContext. response. contentEncoding = Encoding. getEncoding ("UTF-8"); HttpContext. response. charset = "UTF-8"; string fileName = Path. getFileName (fileData. fileName); // the name of the original file string fileExtension = Path. getExtension (fileName); // file extension FileUploadInfo info = new FileUploadInfo (); info. fileData = ReadFileBytes (fileData); if (Info. FileData! = Null) {info. fileSize = info. fileData. length;} info. category = folder; info. fileName = fileName; info. fileExtend = fileExtension; info. attachmentGUID = guid; info. addTime = DateTime. now; info. editor = CurrentUser. name; // logon user // info. owner_ID = OwerId; // The owner Table Record ID result = BLLFactory <FileUpload>. instance. upload (info); if (! Result. success) {LogTextHelper. error ("failed to upload file:" + result. errorMessage);} else {// return the specific path address string serverRealPath = info. basePath. uriCombine (info. savePath); if (! Path. IsPathRooted (info. BasePath )&&! Info. BasePath. StartsWith ("http ://")&&! Info. basePath. startsWith ("https: //") {// if it is a relative directory, add the directory of the current program to locate the file address var url = HttpContext. request. url; var baseurl = url. absoluteUri. replace (url. pathAndQuery, ""); serverRealPath = baseurl. uriCombine (serverRealPath ). replace ('\', '/');} urls. add (serverRealPath) ;}# endregion} catch (Exception ex) {result. errorMessage = ex. message; LogTextHelper. error (ex) ;}} obj. urls = urls;} else {result. errorMessage = "fileData object is blank";} var newResult = new {Success = result. success, ErrorMessage = result. errorMessage, urls = urls}; return ToJsonContent (newResult );}
The interface effect is shown in "Dynamic Display and maintenance of product data by using mini programs and background data management" as I introduced in my essay.
In this case, the Rich Text of the product details is edited to edit the image text, as shown in the following interface.
When we insert an image, a dialog box is displayed. After a file is uploaded, the returned URL is displayed on the SummerNote plug-in.
After the file is uploaded successfully, insert an image using the following code.
$.ajax({ data: data, type: "POST", url: "/FileUpload/Upload", cache: false, contentType: false, processData: false, success: function (json) { var data = $.parseJSON(json); var url = data.urls[0]; $("#Note").summernote('insertImage', url, 'image name'); // the insertImage API } });
The above is how I use the summernote plug-in the actual Bootstrap framework project to edit HTML documents and insert images. The overall structure is easy to use and the experience is for your reference.
For other related documents, refer:
Using the bootstrap fileinput plug-in and the Bootstrap-table plug-in to import Excel Data for file upload, preview, and submission
Metronic-based Bootstrap development framework Experience Summary (16) -- use the plug-in bootstrap-table to Process table records by query, paging, and sorting
Metronic-based Bootstrap development framework Experience Summary (15) -- Updated Metronic 4.75
Starting from the development framework to improve development efficiency
Metronic-based Bootstrap development framework experience (14)-bar code and QR code generation and Printing
Metronic-based Bootstrap development framework Experience Summary (13) -- Implementation of the page Link favorites function 2
Metronic-based Bootstrap development framework Experience Summary (12) -- Implementation of the page Link favorites Function
Metronic-based Bootstrap development framework Experience Summary (11)-page menu display Methods
Metronic-based Bootstrap development framework experience (10) -- Optimizing Bootstrap icon Management
Use dynamic and ExpandoObject In the MVC controller to implement data escape output
Metronic-based Bootstrap development framework Experience Summary (9) -- implement Web page content print preview and save operations
Metronic-based Bootstrap development framework Experience Summary (8)-overall framework function interface Introduction
Metronic-based Bootstrap development framework experience (7) -- data import, export, and attachment viewing
Metronic-based Bootstrap development framework Experience Summary (6) -- handling and optimization of dialog boxes and prompt boxes
Metronic-based Bootstrap development framework Experience Summary (5) -- Use of the Bootstrap File Upload plug-in File Input
Metronic-based Bootstrap development framework experience (4) -- extraction and utilization of Bootstrap icons
Metronic-based Bootstrap development framework experience (3) -- Use of Select2 plug-in the drop-down list
Metronic-based Bootstrap development framework Experience Summary (2) -- list paging processing and use of the plug-in JSTree
Metronic-based Bootstrap development framework Experience Summary (1)-framework overview and menu module processing