2

Hi I have used the code from the following link to allow images to be uploaded to the server. Summernote image upload

Would it be possible to implement something similar to remove an image from the server if a user deletes it from the editor? If so, how can I go about achieving this?

Community
  • 1
  • 1
M9A
  • 3,168
  • 14
  • 51
  • 79

4 Answers4

9

To Delete file form Server, you need to use onMediaDelete but usage varies with different summernote versions, sometimes difficult to find in the docs.

FOR SUMMERNOTE 0.6.x

$(document).ready(function() {
    $('.summernote').summernote({
        height: "300px",
         onMediaDelete : function($target, editor, $editable) {
         alert($target.context.dataset.filename);         
         $target.remove();
    }
    });
});

FOR SUMMERNOTE 0.7.x

$(document).ready(function() {
    $('.summernote').summernote({
        height: "300px",
        onMediaDelete : function(target) {
                deleteFile(target[0].src);
            }

    });
});

FOR SUMMERNOTE 0.8.x (Use Callbacks)

$(document).ready(function() {
    $('#summernote').summernote({
        height: "300px",
        callbacks: {
            onImageUpload: function(files) {
                uploadFile(files[0]);
            },

            onMediaDelete : function(target) {
                // alert(target[0].src) 
                deleteFile(target[0].src);
            }
        }
    });
});

Javascript : Sample to Delete File using img src

function deleteFile(src) {

    $.ajax({
        data: {src : src},
        type: "POST",
        url: base_url+"dropzone/delete_file", // replace with your url
        cache: false,
        success: function(resp) {
            console.log(resp);
        }
    });
}

PHP: Sample to Delete Image afeter retrieving img src

<?php
  $src = $this->input->post('src'); // $src = $_POST['src'];
  $file_name = str_replace(base_url(), '', $src); // striping host to get relative path
        if(unlink($file_name))
        {
            echo 'File Delete Successfully';
        }
?>

enter image description here

This is what I used, its just that, the delete event is not triggered on keypress like backspace, perhaps a keyEvent will handle that in future.

4Jean
  • 765
  • 1
  • 13
  • 25
  • Nice solution but, what happens if someone deletes the image by just using the backspace key?, it seems that the callback doesn't trigger... – Aarón Gutiérrez Feb 06 '19 at 19:52
  • @4Jean, I know it's been a while, but it still doesn't work on my site. I'm using summernote-bs4.min.js and download directly from Summernote official website. could you please tell me which version exactly you were using back that moment? Thanks. – Jack Aug 15 '20 at 17:05
1

I guess you solved the problem by now but as I have been looking for the same answer and finally managed to make it work here is my approach:

First I get all the img src in summernote's textarea then I read all the img files in the folder on the server. After that, I unlink the files in the folder which are not in summernote's img src array.

        $dom = new domDocument;
        $dom->loadHTML(html_entity_decode($content));
        $dom->preserveWhiteSpace = false;
        $imgs  = $dom->getElementsByTagName("img");
        $links = array();
        $path = '../content/'.$id.'/';
        $files = glob($path . "*.*");
        for($i = 0; $i < $imgs->length; $i++) {
           $links[] = $imgs->item($i)->getAttribute("src");
        }
        $result=array_diff($files, $links);
           foreach($result as $deleteFile) {
               if (file_exists($deleteFile)) {
                 array_map('unlink', glob($deleteFile));
               }
           }
       } 

Hope this will help others.

EDIT to answer to @eachone: You can use AJAX too (I do it with jQuery).

$('#DivContainingSummernoteTextarea').blur(function(){
$contentPost = $("#SummernoteTextarea").code();
doAjax('something');
});

I store the content of summernote's textarea in $contentPost. Then doAjax will call the PHP and POST $content. If the img on the server is not in $content it will be deleted.

xamax
  • 53
  • 6
0

If we can catch an event for user's deleting image action on the client side, we can make a ajax call for delete image. but I don't know whether it is or not. I also looking for a solution.

eachone
  • 557
  • 3
  • 11
  • 28
0

In Django i am using regex to find imgs in raw html If i am deleting post, or it has different imgs after editing I am removing them

from traceback import print_exc
import re
import os

def get_imgs(html):
    pat = re.compile(r'<img [^>]*src="([^"]+)')
    imgs = pat.findall(html)
    return imgs

def delete_imgs(imgs):
    if imgs:
        base = os.getcwd()
        for img in imgs:
            try:
                img_path = os.path.join(base, img[1:])
                if os.path.exists(img_path):
                    os.remove(img_path)
            except Exception as e:
                print_exc(e)
                print(imgs)
                print(img_path)
Vargan
  • 41
  • 2