Search code examples
javascriptjqueryhtmlwysiwygsummernote

Insert uploaded image to summernote editor


My objective is to insert the uploaded image(local file) to the summernote editor.

Image uploading successfully, only need to insert into the editor.

I was trying to console log the editor instance, but it's showing undefined. If I can pass the editor instance to the sendFile function, I think the issue will be resolved.

jsfiddle

$(document).ready(function () {

  $('.summernote').summernote({
    callbacks: {
     onImageUpload: function(files, editor, welEditable) {
      var url= sendFile(files[0], editor, welEditable);
    }
  },
  height: 300,
  focus: true,

});

  function sendFile(file, editor, welEditable) {
    data = new FormData();
    data.append("file", file);
    console.log(editor);
    /* $.ajax({
      data: data,
      type: "POST",
      url: "Test/test",
      cache: false,
      contentType: false,
      processData: false,
      success: function(url) {
        editor.insertImage(welEditable, url);
        console.log(url); //eg:https://server-url/assets/images/a8f15ed.jpg
      },
      error: function(jqXHR, stat, err){
        console.log(stat+':'+err);
      }
    }); */
  }
});
<head> 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote-bs4.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote-bs4.js"></script>
</head>


<div class="container">
  <div class="row">
    <div class="col-md-3">
      <div class="col-md-4">
        <div class="summernote"></div>
      </div>
    </div>
  </div>
</div>


Solution

  • On ajax success, we can insert the image to the editor instance by this way

    success: function(url) {
      $('#summernote').summernote("insertImage", url, 'filename');
    },
    

    Don't need to insert into the editor from sendFile(file, editor, welEditable) function param. For my case this solves the porblem.

    Helpful comment