Tinymce editor add image upload button

TinyMCE is one of the best Wysiwyg editor used for content writing. This editor is available free to use but in the free version, it provides only image URL option instead of uploading an image. You won’t like to first upload an image on your hosting image upload folder and then provide it a full path.

Tinymce editor add image upload button

So, I am going to tell you how can you add upload button to your editor like in the above image.

TinyMCE Add Button

TinyMCE’s setup function will be used to create a button. There we have to call addButton function to add a button to the toolbar. Then we’ll trigger a dynamic input field to upload a file. See the below code, copy and paste this code in the TinyMCE init function.

setup: function(editor) {

 var base = 'http://onegibi.com/';
 
 function uploadFile( file ) { 
     var data = new FormData();
     data.append('file', file);
     $.ajax({
         type: 'POST',
         data: data,
         url: url + 'upload.php',
         contentType: false,
         processData: false,
         cache: false,
         success: function(res) {
             editor.insertContent(res);
         },
         error: function(xhr, ajaxOptions, thrownError) {
             editor.insertContent('<p>'+xhr.responseText+' '+thrownError+'</p>');
         }
     });
  }
  editor.addButton( 'fileupload', {
     text:"Image",
     icon: false,
     onclick: function(e) {
         $input = $('<input type="file" class="editorattachment">');
         $($input).click();
         $($input).on('change', function(e){
              file = $($input)[0].files[0];
              uploadFile( file );
         });
     }
  });
}

PHP Code

Now create an upload.php file and write the below code.

if( isset( $_FILES['file'] ) ) {

   $tmp_name = $_FILES['file']['tmp_name'];
   $destination = '/img/' . $_FILES['file']['name'];
 
   move_uploaded_file($tmp_name, $destination);
}

 

 

Comments

Be the first to comment