upload image from local into tinyMCE

后端 未结 8 829
小鲜肉
小鲜肉 2021-02-04 02:33

tinyMCE has an insert image button, but how to handle its functionality pls give some code

8条回答
  •  爱一瞬间的悲伤
    2021-02-04 03:02

    I used pavanastechie's and Chris Lear's solutions, which worked perfectly for me, and wanted to share a complete example built on theirs that uploads the image to the server and embeds the image using the URL provided back by the server:

    tinymce.init({
      toolbar: 'imageupload',
      setup: function(editor) {
        initImageUpload(editor);
      }
    });
    
    function initImageUpload(editor) {
      // create input and insert in the DOM
      var inp = $('');
      $(editor.getElement()).parent().append(inp);
    
      // add the image upload button to the editor toolbar
      editor.addButton('imageupload', {
        text: '',
        icon: 'image',
        onclick: function(e) { // when toolbar button is clicked, open file select modal
          inp.trigger('click');
        }
      });
    
      // when a file is selected, upload it to the server
      inp.on("change", function(e){
        uploadFile($(this), editor);
      });
    }
    
    function uploadFile(inp, editor) {
      var input = inp.get(0);
      var data = new FormData();
      data.append('image[file]', input.files[0]);
    
      $.ajax({
        url: '/admin/images',
        type: 'POST',
        data: data,
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR) {
          editor.insertContent('');
        },
        error: function(jqXHR, textStatus, errorThrown) {
          if(jqXHR.responseText) {
            errors = JSON.parse(jqXHR.responseText).errors
            alert('Error uploading image: ' + errors.join(", ") + '. Make sure the file is an image and has extension jpg/jpeg/png.');
          }
        }
      });
    }
    

提交回复
热议问题