Summernote - upload image after submit
Asked Answered
D

1

5

I need help with uploading a photo (along with other inserted data in editor) but only when submit button is clicked. I've searched forum, and googled but no luck :(

The code I'm using is working for uploading image and saving text to database, but it's uploading image instantly when I add it to editor. This is not desired behavior for me, 'couse if user add image to editor and then decide to close tab/close browser or go to another address, image will be stored on server - so I would like someone to help me to upload image only when submitt button is pressed (until then, it will be there only as preview). Here is my code:

$('#summernote').summernote({
   //placeholder: 'your Message',

   height: 200,
        toolbar: [
            ['style', ['style']],
            ['font', ['bold', 'italic', 'underline', 'clear']],
            ['fontname', ['fontname']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['height', ['height']],
            ['table', ['table']],
            ['insert', ['link', 'picture', 'hr']],
            ['view', ['fullscreen', 'codeview', 'help']],
            ['save-button', ['save']]
        ],
        callbacks : {
            onImageUpload: function(image) {
                uploadImage(image[0]);
            }
        }
});

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

$(".note-save-button").addClass("pull-right");

$(function(){
    $('#addit_dtls_form').submit(function(event){

        var input_content = $('#summernote').summernote('code');
        var is_empty = $("#is_empty").val();
        var location_id = $("#location_id").val();;
        //event.preventDefault();
        $.ajax({ 
            url: 'url - store text to database',
            type: 'post',
            data: { 
                'input_content' : input_content, 
                'is_empty' : is_empty,
                'location_id' : location_id,
            }, 

            success: function(response){ 
                $.smallBox({
                        title : "USPEŠNO!",
                        content : "Sadržaj je uspešno snimljen!",
                        color : "#7DC27D",
                        timeout: 4000,
                        icon : "fa fa-check"
                });
                //console.log(input_content);

            }
        });
    });
});

Hope someone can help me, or there is some example code someone can point me to. Tnx in advance!

Dactylogram answered 2/2, 2018 at 15:29 Comment(1)
I'm wanting to do the exact same thing -- my image uploads are working perfectly, however, for very large images it takes a few seconds. I'd rather the image showed in the editor immediately (like they do when base64 and the default behavior) and then only upload when the editor text is submitted. Came here hoping you'd found an answer. :-) I'll let you know if I ever figure this out...Brag
B
6

So, I was actually able to achieve this functionality, however, it's entirely outside of Summernote.

TL;DR:

  1. On Summernote submit, intercept the submitted html (Summernote sends the editor contents as html) before saving it to the database
  2. Search for base64 images in the intercepted html
  3. If base64-encoded images are found, decode them, convert them to image files, and save them to disk
  4. Parse the original html, replacing the tag's src attribute with the url of your newly saved images
  5. Save the final html to the database like normal

Code:

I'm doing this in PHP. My application is a forum software where the html page posts to a PHP page and within that page we save the submitted text. So, in this file we're adding this:

....
// The text from Summernote here is saved in a variable called $submitted_text
....
// This if-statement could probably be better, but this is working well for me so far
if (strpos($submitted_text, '<img') !== false && strpos($submitted_text, ';base64') !== false) {

    $doc = new DOMDocument();
    $doc->loadHTML($submitted_text);

    $tags = $doc->getElementsByTagName('img');

    foreach ($tags as $tag) {
        // Get base64 encoded string
        $srcStr = $tag->getAttribute('src');
        $base64EncData = substr($srcStr, ($pos = strpos($srcStr, 'base64,')) !== false ? $pos + 7 : 0);
        $base64EncData = substr($base64EncData, 0, -1);

        // Get an image file
        $img = base64_decode($base64EncData);

        // Get file type
        $dataInfo = explode(";", $srcStr)[0];
        $fileExt = str_replace('data:image/', '', $dataInfo);

        // Create a new filename for the image
        $newImageName = str_replace(".", "", uniqid("forum_img_", true));
        $filename = $newImageName . '.' . $fileExt;
        $file = '/media/storage/public/uploaded_imgs/' . $filename;

        // Save the image to disk
        $success = file_put_contents($file, $img);
        $imgUrl = 'https://www.yourdomain.com/uploaded_imgs/' . $filename;

        // Update the forum thread text with an img tag for the new image
        $newImgTag = '<img src="' . $imgUrl . '" />';

        $tag->setAttribute('src', $imgUrl);
        $tag->setAttribute('data-original-filename', $tag->getAttribute('data-filename'));
        $tag->removeAttribute('data-filename');
        $submitted_text = $doc->saveHTML();
    }
}

// Here, $submitted_text is now the modified html/text you'll want to save to your database. Huzzah! Handle anything else needed before saving the text here.

Note that this means that we don't need any callbacks for Summernote itself -- we're using the default image handling with the base64 encodings.

Brag answered 3/11, 2018 at 19:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.