Add Browse Button and Upload File in TinyMCE

In TinyMCE editor to view image and media options in the menu or in toolbar need to load them by using plugins option while initializing.

This adds them to the editor but you can load external file by passing the source path. It does not allow to browse any file within the system.

The browse button easily added by defining file_picker_callback option.

This only adds browse button but not allow file selection.

Within the file_picker_callback function need to write the script to enable file selection and upload the file to the server.

For upload the file to the server I am using PHP.

Add Browse Button and Upload File in TinyMCE


Contents

  1. Download and Include
  2. HTML
  3. PHP
  4. Script
  5. Conclusion

1. Download and Include

  • Download TinyMCE and include tinymce.min.js with jQuery library in the <head> section.
<script src='tinymce/js/tinymce/tinymce.min.js' type='text/javascript'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

2. HTML

Create a <textarea> element and <input type='file' > element.

Here,  <input type='file'> is used to select a file when a browse button clicks on the TinyMCE editor. This will trigger from the jQuery.

Completed Code

<textarea ></textarea>
<input type='file' name='fileupload' id='fileupload' style='display: none;'>

3. PHP

Create upload.php file and upload directory for storing files.

According to $filetype value set $valid_ext array. If the extension is valid then store file in upload directory and assign file name in $return_filename.

Completed Code

<?php

// Getting file name
$filename = $_FILES['file']['name'];

// file type
$filetype = $_POST['filetype'];

// Valid extension
if($filetype == 'image'){
  $valid_ext = array('png','jpeg','jpg');
}else if($filetype == 'media'){
  $valid_ext = array('mp4','mp3');
}

// Location
$location = "upload/".$filename;

// file extension
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);

$return_filename = "";

// Check extension
if(in_array($file_extension,$valid_ext)){
 
  // Upload file
  if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
 
    $return_filename = $filename;

  }

}

echo $return_filename;

4. Script

Initialize TinyMCE editor on the <textarea> by calling init() method.

To enable image and media file selection define plugins: 'image media'.

Define file_picker_callback option to add browse button.

Within the function check meta.filetype if it is ‘image’ or ‘media’ then trigger click event on the <input type='file'> and on change get the file and append in FormData object where also append meta.filetype.

Pass the FormData object in the AJAX request for upload if a file is successfully uploaded then assign response in filename variable.

Use the filename in reader.onload() method.

Completed Code

tinymce.init({
  selector: 'textarea',
  themes: 'modern',
  height: 200,
  plugins: "image media",
  file_picker_callback: function(callback, value, meta) {
    // File type
    if (meta.filetype =="media" || meta.filetype =="image") {

      // Trigger click on file element
      jQuery("#fileupload").trigger("click");
      $("#fileupload").unbind('change');
      // File selection
      jQuery("#fileupload").on("change", function() {
         var file = this.files[0];
         var reader = new FileReader();
		                
         // FormData
         var fd = new FormData();
         var files = file;
         fd.append("file",files);
         fd.append('filetype',meta.filetype);

         var filename = "";
		                
         // AJAX
	 jQuery.ajax({
            url: "upload.php",
	    type: "post",
	    data: fd,
	    contentType: false,
	    processData: false,
	    async: false,
	    success: function(response){
	       filename = response;
            }
         });
		             
	 reader.onload = function(e) {
            callback("upload/"+filename);
	 };
         reader.readAsDataURL(file);
       });
     }
		        
   }
 
  }

});

5. Conclusion

Use file_picker_callback option to add browse button and to enable file selection create a <input type='file'> element.

Trigger click event when browse button gets clicked and use AJAX to store file.

If you found this tutorial helpful then don't forget to share.