Summernote image upload
Asked Answered
R

6

55

I have a problem with editor Summernote. I want to upload images into a catalog on the server. I have some script:

<script type="text/javascript">
  $(function () {
    $(\'.summernote\').summernote({
      height: 200
    });
    $(\'.summernote\').summernote({
     height:300,
     onImageUpload: function(files, editor, welEditable) {
      sendFile(files[0],editor,welEditable);
    }
  });

  });
</script>
<script type="text/javascript">
  function sendFile(file, editor, welEditable) {
    data = new FormData();
    data.append("file", file);
    url = "http://localhost/spichlerz/uploads";
    $.ajax({
      data: data,
      type: "POST",
      url: url,
      cache: false,
      contentType: false,
      processData: false,
      success: function (url) {
        editor.insertImage(welEditable, url);
      }
    });
  }
</script>



<td><textarea class="summernote" rows="10" cols="100" name="tekst"></textarea></td>

Of course, I have all js and CSS files. What I do wrong? If I click on image upload and go to the editor, the image is not in textarea.

If I delete sendFile function and onImageUpload: the image save on base64.

Link to summernote: http://hackerwins.github.io/summernote/

Ronn answered 7/2, 2014 at 12:48 Comment(0)
A
64

I tested this code and Works

Javascript

<script>
$(document).ready(function() {
  $('#summernote').summernote({
    height: 200,
    onImageUpload: function(files, editor, welEditable) {
      sendFile(files[0], editor, welEditable);
    }
  });

  function sendFile(file, editor, welEditable) {
    data = new FormData();
    data.append("file", file);
    $.ajax({
      data: data,
      type: "POST",
      url: "Your URL POST (php)",
      cache: false,
      contentType: false,
      processData: false,
      success: function(url) {
        editor.insertImage(welEditable, url);
      }
    });
  }
});
</script>

PHP

if ($_FILES['file']['name']) {
  if (!$_FILES['file']['error']) {
    $name = md5(rand(100, 200));
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    $filename = $name.
    '.'.$ext;
    $destination = '/assets/images/'.$filename; //change this directory
    $location = $_FILES["file"]["tmp_name"];
    move_uploaded_file($location, $destination);
    echo 'http://test.yourdomain.al/images/'.$filename; //change this URL
  } else {
    echo $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
  }
}

Update:

After 0.7.0 onImageUpload should be inside callbacks option as mentioned by @tugberk

$('#summernote').summernote({
    height: 200,
    callbacks: {
        onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0], editor, welEditable);
        }
    }
});
Aron answered 23/3, 2014 at 9:22 Comment(6)
Works well, good job - NOTE: make sure $destination is absolute pathPadishah
Hey ... what about if you delete an image ?Nauru
url: "Your URL POST (php)" Which url should be here? I tried putting the url of the php upload function in codeigniter, but that doesnt work.Outstretch
this is the most voted answer but will not work with v0.8.8, see summernote.org/deep-dive/#onimageupload. You might want to update your answer since it took me a few hours to figure it out :sThirtytwo
What will happen in multi upload situation?Concomitance
Is it necessary? we will have to create upload.php .Insolvency
G
52

Image Upload for Summernote v0.8.1

for large images

$('#summernote').summernote({
    height: ($(window).height() - 300),
    callbacks: {
        onImageUpload: function(image) {
            uploadImage(image[0]);
        }
    }
});

function uploadImage(image) {
    var data = new FormData();
    data.append("image", image);
    $.ajax({
        url: 'Your url to deal with your image',
        cache: false,
        contentType: false,
        processData: false,
        data: data,
        type: "post",
        success: function(url) {
            var image = $('<img>').attr('src', 'http://' + url);
            $('#summernote').summernote("insertNode", image[0]);
        },
        error: function(data) {
            console.log(data);
        }
    });
}
Gilcrest answered 9/6, 2016 at 15:14 Comment(1)
How can I upload images directly from URL? I want to replace inserted image link to my server path after file downloaded to my server.Radioactive
E
26

UPLOAD IMAGES WITH PROGRESS BAR

Thought I'd extend upon user3451783's answer and provide one with an HTML5 progress bar. I found that it was very annoying uploading photos without knowing if anything was happening at all.

HTML

<progress></progress>

<div id="summernote"></div>

JS

// initialise editor

$('#summernote').summernote({
        onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0], editor, welEditable);
        }
});

// send the file

function sendFile(file, editor, welEditable) {
        data = new FormData();
        data.append("file", file);
        $.ajax({
            data: data,
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
                return myXhr;
            },
            url: root + '/assets/scripts/php/app/uploadEditorImages.php',
            cache: false,
            contentType: false,
            processData: false,
            success: function(url) {
                editor.insertImage(welEditable, url);
            }
        });
}

// update progress bar

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded, max:e.total});
        // reset progress on complete
        if (e.loaded == e.total) {
            $('progress').attr('value','0.0');
        }
    }
}
Eleonoreleonora answered 4/8, 2014 at 15:45 Comment(4)
Progress bar is not working with latest version, have you got it working with new version of summernote?Lunatic
@star18bit: It should work - the progress bar feature I added has nothing to do with Summernote, I'm just listening to the progress of the XMLHttpRequest when the file sends.Eleonoreleonora
working perfectly with latest summernote. a neat solution to the problem. Thanks a ton.Idalia
I don't think this works with the currrent version. The two variables editor and welEditable are always null. EDIT: see github.com/vsymguysung/ember-cli-summernote/issues/31Falcongentle
C
13

This code worked well with new version (v0.8.12) (2019-05-21)

$('#summernote').summernote({
        callbacks: {
            onImageUpload: function(files) {
                for(let i=0; i < files.length; i++) {
                    $.upload(files[i]);
                }
            }
        },
        height: 500,
    });

    $.upload = function (file) {
        let out = new FormData();
        out.append('file', file, file.name);

        $.ajax({
            method: 'POST',
            url: 'upload.php',
            contentType: false,
            cache: false,
            processData: false,
            data: out,
            success: function (img) {
                $('#summernote').summernote('insertImage', img);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(textStatus + " " + errorThrown);
            }
        });
    };

PHP Code (upload.php)

if ($_FILES['file']['name']) {
 if (!$_FILES['file']['error']) {
    $name = md5(rand(100, 200));
    $ext = explode('.', $_FILES['file']['name']);
    $filename = $name . '.' . $ext[1];
    $destination = 'images/' . $filename; //change this directory
    $location = $_FILES["file"]["tmp_name"];
    move_uploaded_file($location, $destination);
    echo 'images/' . $filename;//change this URL
 }
 else
 {
  echo  $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
 }
}
Covalence answered 21/5, 2019 at 10:4 Comment(1)
Thank you Namal! By any chance did you figure out code for handling deletions and removing from the server directory? If so, would appreciate a posting. Thanks!Inkblot
I
1

Summernote converts your uploaded images to a base64 encoded string by default, you can process this string or as other fellows mentioned you can upload images using onImageUpload callback. You can take a look at this gist which I modified a bit to adapt laravel csrf token here. But that did not work for me and I had no time to find out why! Instead, I solved it via a server-side solution based on this blog post. It gets the output of the summernote and then it will upload the images and updates the final markdown HTML.

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

Route::get('/your-route-to-editor', function () {
    return view('your-view');
});

Route::post('/your-route-to-processor', function (Request $request) {

       $this->validate($request, [
           'editordata' => 'required',
       ]);

       $data = $request->input('editordata');

       //loading the html data from the summernote editor and select the img tags from it
       $dom = new \DomDocument();
       $dom->loadHtml($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);    
       $images = $dom->getElementsByTagName('img');
       
       foreach($images as $k => $img){
           //for now src attribute contains image encrypted data in a nonsence string
           $data = $img->getAttribute('src');
           //getting the original file name that is in data-filename attribute of img
           $file_name = $img->getAttribute('data-filename');
           //extracting the original file name and extension
           $arr = explode('.', $file_name);
           $upload_base_directory = 'public/';

           $original_file_name='time()'.$k;
           $original_file_extension='png';

           if (sizeof($arr) ==  2) {
                $original_file_name = $arr[0];
                $original_file_extension = $arr[1];
           }
           else
           {
                //the file name contains extra . in itself
                $original_file_name = implode("_",array_slice($arr,0,sizeof($arr)-1));
                $original_file_extension = $arr[sizeof($arr)-1];
           }

           list($type, $data) = explode(';', $data);
           list(, $data)      = explode(',', $data);

           $data = base64_decode($data);

           $path = $upload_base_directory.$original_file_name.'.'.$original_file_extension;

           //uploading the image to an actual file on the server and get the url to it to update the src attribute of images
           Storage::put($path, $data);

           $img->removeAttribute('src');       
           //you can remove the data-filename attribute here too if you want.
           $img->setAttribute('src', Storage::url($path));
           // data base stuff here :
           //saving the attachments path in an array
       }

       //updating the summernote WYSIWYG markdown output.
       $data = $dom->saveHTML();

       // data base stuff here :
       // save the post along with it attachments array
       return view('your-preview-page')->with(['data'=>$data]);

});
Indentation answered 6/8, 2019 at 15:43 Comment(1)
by a nonsense string, I meant base64 encrypted data.Indentation
I
-1

I tried almost all answers in here and none of them worked for me in v0.8.18.

I found a simple solution tought someone might need it.

Here it is:

Open your js summernote/summernote-lite.js and find onImageUpload: null,.

Replace with :

onImageUpload: function(files) {
var $editor = $(this);
var data = new FormData();
 data.append('file', files[0]);
 $.ajax({
     url: 'editor-upload.php',
     method: 'POST',
     data: data,
     processData: false,
     contentType: false,
     success: function(response) {
       $editor.summernote('insertImage', response);
     }
 });
},

Simple php example : editor-upload.php

if(empty($_FILES['file']))
{
    echo "Insert image";
}

$errorImgFile = "img/img_upload_error.jpg";
$destinationFilePath = 'img-uploads/'.$_FILES['file']['name'];
if(!move_uploaded_file($_FILES['file']['tmp_name'], $destinationFilePath)){
    echo $errorImgFile;
}
else{
    echo $destinationFilePath;
}

Clear browsing data and refresh page, That is it, it works like a charm.

Note : I dont use minified version, so be carefull, and backup your file first.

Interrelate answered 3/5, 2022 at 22:39 Comment(1)
Why one would modify original source code? You would have to redo it every time a new version is published any there are already many answers that show what to do!Zilla

© 2022 - 2024 — McMap. All rights reserved.