1 Star2 Stars3 Stars4 Stars5 Stars (7 votes, average: 5.00 out of 5)

Store Image Uploads On Server With Summernote Not Base 64

Store Image Uploads On Server With Summernote Not Base 64

If you do image uploads through Summernote you will notice that it stores base 64 code for the image. If you are saving that kind of code in your database you will notice that it bloats the database. This will cause lag time on your server. The much better option is upload the image to the file system and store the actual image in a directory.

Setting Up To Store Image Uploads On Server With Summernote Not Base 64 *

Let us set up our server to store images though summernote on a directory. First we will create 2 files and one folder on our server.

Create The Index.php File *

Create an index.php file on your server. Here is the code. Be sure to include the html language tag as well as the doctype.

<html lang="en"><!DOCTYPE html>
<html>
<head>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> 
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script> 

<!-- include summernote css/js -->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>
</head>
<body>
<div class="container">
<form>
<textarea id="summernote"></textarea>
</form>
</div>
<script>$(document).ready(function() {
$("#summernote").summernote({
  placeholder: 'enter directions here...',
        height: 300,
         callbacks: {
        onImageUpload : function(files, editor, welEditable) {

             for(var i = files.length - 1; i >= 0; i--) {
                     sendFile(files[i], this);
            }
        }
    }
    });
});
function sendFile(file, el) {
var form_data = new FormData();
form_data.append('file', file);
$.ajax({
    data: form_data,
    type: "POST",
    url: 'editor-upload.php',
    cache: false,
    contentType: false,
    processData: false,
    success: function(url) {
        $(el).summernote('editor.insertImage', url);
    }
});
}
</script>
</body>
</html>

Create editor-upload.php File *

Now Create editor-upload.php file. This is what will process the image file for you. Here is what it looks like.

<?php 
if(empty($_FILES['file']))
{
	exit();	
}
$errorImgFile = "./img/img_upload_error.jpg";
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$destinationFilePath = './img-uploads/'.$newfilename ;
if(!move_uploaded_file($_FILES['file']['tmp_name'], $destinationFilePath)){
	echo $errorImgFile;
}
else{
	echo $destinationFilePath;
}

?>

Create img-uploads Directory *

Now create a folder and call it img-uploads. This is the folder we will be storing the images in. Make sure it has permissions to store files.

Just in case muy WordPress corrupts my code here you can download the files here.

Summernote Image Upload On The Fly

Please follow and like us:
Store Image Uploads On Server With Summernote Not Base 64 was last modified: April 26th, 2018 by Maximus Mccullough

4 Comments

  • Davo says:

    I’ve used your code with some success thanks for that BUT (yes there’s always a but).

    If i try to upload multiple image files say 10 images, 10 images will be displayed in the summernote edit box but some will be duplicates, you might have 8 of the same and 2 of another and only those 2 files will have actually been uploaded to the server.

    If I debug the code in Chrome and put a break in the for loop where the file list array is loaded one at a time using ajax, I can see each image being loaded and they all go up just fine. When not in the debugger I get the aforementioned problem. It’s like the ajax call is not getting time to complete or something, any ideas?

    • Yeah thats an interesting problem. I think that may be an issue with the PHP uploader page. I don’t have time to look right now but in the upload php there may be an issue. Here are a couple multi uploaders to try.

      Without Validation

      foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name){
          $temp = $_FILES["files"]["tmp_name"][$key];
          $name = $_FILES["files"]["name"][$key];
           
          if(empty($temp))
          {
              break;
          }
           
          move_uploaded_file($temp,"UploadFolder/".$name);
      }

      With Validation

      $errors = array();
      $uploadedFiles = array();
      $extension = array("jpeg","jpg","png","gif");
      $bytes = 1024;
      $KB = 1024;
      $totalBytes = $bytes * $KB;
      $UploadFolder = "UploadFolder";
       
      $counter = 0;
       
      foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name){
          $temp = $_FILES["files"]["tmp_name"][$key];
          $name = $_FILES["files"]["name"][$key];
           
          if(empty($temp))
          {
              break;
          }
           
          $counter++;
          $UploadOk = true;
           
          if($_FILES["files"]["size"][$key] > $totalBytes)
          {
              $UploadOk = false;
              array_push($errors, $name." file size is larger than the 1 MB.");
          }
           
          $ext = pathinfo($name, PATHINFO_EXTENSION);
          if(in_array($ext, $extension) == false){
              $UploadOk = false;
              array_push($errors, $name." is invalid file type.");
          }
           
          if(file_exists($UploadFolder."/".$name) == true){
              $UploadOk = false;
              array_push($errors, $name." file is already exist.");
          }
           
          if($UploadOk == true){
              move_uploaded_file($temp,$UploadFolder."/".$name);
              array_push($uploadedFiles, $name);
          }
      }
       
      if($counter>0){
          if(count($errors)>0)
          {
              echo "<b>Errors:</b>";
              echo "<br/><ul>";
              foreach($errors as $error)
              {
                  echo "<li>".$error."</li>";
              }
              echo "</ul><br/>";
          }
           
          if(count($uploadedFiles)>0){
              echo "<b>Uploaded Files:</b>";
              echo "<br/><ul>";
              foreach($uploadedFiles as $fileName)
              {
                  echo "<li>".$fileName."</li>";
              }
              echo "</ul><br/>";
               
              echo count($uploadedFiles)." file(s) are successfully uploaded.";
          }                               
      }
      else{
          echo "Please, Select file(s) to upload.";
      }
  • Eko Budiyanto says:

    Work great, thank you for great tutorial, anyway is it possible to delete image when user remove the image from the editor? thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.