summernote js upload image

I'm using summernote version 0.8.1 (current).

It's working. But 1 thing I struggle with. Inserting an image, rather than putting base64 dataURL, I want to upload the image to the server and insert the image URL in the database. This is my code:

<script>
$(document).ready(function() {
$('#summernote').summernote({
    lang: 'fr-FR',
    height: 300,
    toolbar : [
        ['style',['bold','italic','underline','clear']],
        ['font',['fontsize']],
        ['color',['color']],
        ['para',['ul','ol','paragraph']],
        ['link',['link']],
        ['picture',['picture']]
    ],
    onImageUpload: function(files, editor, welEditable) {
        for (var i = files.lenght - 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: "../up.php",
        cache: false,
        contentType: false,
        processData: false,
        success: function(url) {
            $(el).summernote('editor.insertImage',url);
            }
        })
    }

});
    </script>

I have tested the script up.php and what that does is changing the file name and returning the image's url in the form "../photos/mypicture.jpg".

The problem with the above code is that the ..up.php doesn't even seem to be called. I ran this in Firefox development tools and got no errors or warnings.

Answers:

Answer

I got it working. Here's my code. Using summernote 0.8.1, i.e. current version.

<script>

$(document).ready(function() {

var IMAGE_PATH = 'http://www.path/to/document_root/';
                  // the exact folder in the document_root
                  // will be provided by php script below

$('#summernote').summernote({
    lang: 'fr-FR', // <= nobody is perfect :)
    height: 300,
    toolbar : [
        ['style',['bold','italic','underline','clear']],
        ['font',['fontsize']],
        ['color',['color']],
        ['para',['ul','ol','paragraph']],
        ['link',['link']],
        ['picture',['picture']]
    ],
    callbacks : {
        onImageUpload: function(image) {
            uploadImage(image[0]);
        }
    }
});

function uploadImage(image) {
    var data = new FormData();
    data.append("image",image);
    $.ajax ({
        data: data,
        type: "POST",
        url: "../up.php",// this file uploads the picture and 
                         // returns a chain containing the path
        cache: false,
        contentType: false,
        processData: false,
        success: function(url) {
            var image = IMAGE_PATH + url;
            $('#summernote').summernote("insertImage", image);
            },
            error: function(data) {
                console.log(data);
                }
        });
    }

});
</script>

Here my up.php :

<?php
require('admchir/nettoie.php'); 
      // nettoie.php removes the French special chars and spaces
$image = nettoie($_FILES['image']['name']);
$uploaddir = 'photos/';
      // that's the directory in the document_root where I put pics
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
    echo$uploadfile;
} else {
    echo "Lo kol kakh tov..."; // <= nobody is perfect :)
}
?>

From looking for this on the internet, I got the impression that summernote changed a lot between the various versions, but didn't find a full working example of the current version. Hope this helps someone.

Answer

This is how I integrated it with Codeigniter 3, Summernote 0.8.1:

I am posting my working solution here so that anyone else can get some help or idea on how to implement summernote with image upload in CI 3 with CSRF.

the javascript code:

<!-- include libraries(jQuery, bootstrap) -->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/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.1/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.js"></script>

<script>
$(document).ready(function () {
    $('#content').summernote({
        height: 400,
        callbacks: {
            onImageUpload: function (image) {
                sendFile(image[0]);
            }
        }

    });
    function sendFile(image) {
        var data = new FormData();
        data.append("image", image);
        //if you are using CI 3 CSRF
        data.append("<?= $this->security->get_csrf_token_name() ?>", "<?= $this->security->get_csrf_hash() ?>");
        $.ajax({
            data: data,
            type: "POST",
            url: "<?= site_url('summernote-image-upload') ?>",
            cache: false,
            contentType: false,
            processData: false,
            success: function (url) {
                var image = url;
                $('#content').summernote("insertImage", image);
            },
            error: function (data) {
                console.log(data);
            }
        });
    }
});
</script>

the codeigniter part:

 //add this line in your routes.php
 $route['summernote-image-upload'] = 'welcome/summernote-image-upload';

 //now add this method in your Welcome.php Controller:
 function summernote_image_upload() {
    if ($_FILES['image']['name']) {
        if (!$_FILES['image']['error']) {
            $ext = explode('.', $_FILES['image']['name']);
            $filename = underscore($ext[0]) . '.' . $ext[1];
            $destination = './public/images/summernote/' . $filename; //change path of the folder...
            $location = $_FILES["image"]["tmp_name"];
            move_uploaded_file($location, $destination);
            echo base_url() . 'public/images/summernote/' . $filename;
        } else {
            echo $message = 'The following error occured:  ' . $_FILES['image']['error'];
        }
    }
}

the HTML part:

   <textarea name="content" id="content"><?= html_entity_decode(set_value('content')) ?></textarea>
   <?= form_error('content') ?>

note if you face issue with CSRF (for any reason), then you can exclude the summernote ajax upload in your config.php file:

 $config['csrf_exclude_uris'] = array('summernote-image-upload');

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.