Using ckeditor and dotnetcore to upload pictures

Time:2021-4-20

This example for you to share the ckeditor and dotnetcore image upload specific code, for your reference, the specific content is as follows

Using ckeditor

1. Introduce JS library


<script src="https://cdn.ckeditor.com/4.6.1/standard-all/ckeditor.js"></script> 

2. Define a textarea label


<textarea>
 </textarea> 

3. Replace textarea with ckeditor to use basic functions


CKEDITOR.replace('editor'); 

4. Configure ckeditor

Add image upload, code insertion tool

CKEDITOR.replace('editor-box', {
   // GitHub address: HTTPS :// github . com / ckeditor   
   toolbar: [
    { name: 'document', items: ['Source'] },
    { name: 'basicstyles', items: ['Bold', 'Italic'] },
    { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote'] },
    { name: 'links', items: ['Link', 'Unlink'] },
    { name: 'insert', items: ['Image','CodeSnippet'] },
    { name: 'styles', items: ['Format', 'Styles'] }
   ],
   Filebrowserimageuploadurl: '/ blogs / uploadimageurl' // configure background URL for image upload   
   customConfig: '',   
   extraPlugins: 'codesnippet,image2,uploadimage',   
   removePlugins: 'image',   
   //mathJaxLib: 'https://cdn.mathjax.org/mathjax/2.6-latest/MathJax.js?config=TeX-AMS_HTML',  
   codeSnippet_theme: 'ir_black',
   height: 450,   
   contentsCss: ['https://cdn.ckeditor.com/4.6.1/standard-all/contents.css'],   
   format_tags: 'p;h1;h2;h3;pre',   
   removeDialogTabs: 'image:advanced;link:advanced;link:target',  
   stylesSet: [
    /* Inline Styles */
    { name: 'Marker', element: 'span', attributes: { 'class': 'marker' } },
    { name: 'Cited Work', element: 'cite' },
    { name: 'Inline Quotation', element: 'q' },
    /* Object Styles */
    {
     name: 'Special Container',
     element: 'div',
     styles: {
      padding: '5px 10px',
      background: '#eee',
      border: '1px solid #ccc'
     }
    },
    {
     name: 'Compact table',
     element: 'table',
     attributes: {
      cellpadding: '5',
      cellspacing: '0',
      border: '1',
      bordercolor: '#ccc'
     },
     styles: {
      'border-collapse': 'collapse'
     }
    },
    { name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } },
    { name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } },
    /* Widget Styles */
    { name: 'Illustration', type: 'widget', widget: 'image', attributes: { 'class': 'image-illustration' } },
    { name: 'Featured snippet', type: 'widget', widget: 'codeSnippet', attributes: { 'class': 'code-featured' } },
    { name: 'Featured formula', type: 'widget', widget: 'mathjax', attributes: { 'class': 'math-featured' } }
   ]
  });

5. Receiving pictures in the background

/// <summary>
  ///Picture upload
  /// </summary>
  /// <param name="env"></param>
  /// <returns></returns>
  public async Task<IActionResult> UploadImageUrl([FromServices]IHostingEnvironment env)
  {
   //A very important parameter submitted by ckeditor 
   string callback = Request.Query["CKEditorFuncNum"];
   var form = Request.Form;
   var img =  form.Files [0]; // get pictures
   string fileName = img.FileName;
   var openReadStream = img.OpenReadStream();
   byte[] buff = new byte[openReadStream.Length];
   await openReadStream.ReadAsync(buff, 0, buff.Length);
   string filenameGuid = Guid.NewGuid().ToString();
   var bowerPath  =  PathUtils . GetSavePath ( filenameGuid ,  true ) + ". jpg ";// Get the path to save the picture, here according to their own implementation
   var savePath = Path.Combine(env.WebRootPath, bowerPath);
   using (FileStream fs = new FileStream(savePath, FileMode.Create))
   {
    await fs.WriteAsync(buff, 0, buff.Length);
    //The server returns a JavaScript script
    string result = $"<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(\"{callback}\", \"{"/"+bowerPath}\", \"\");</script>";
    Response.ContentType = "text/html;charset=UTF-8";
    return Content(result);
   }
  }

six . be careful

This should be added to the server return, otherwise the front-end page will not execute the returned JavaScript script


Response.ContentType = "text/html;charset=UTF-8";

After configuration, you can use the image upload function

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.