How to make Image Upload in Summernote Editor?

1. Add this script in your html page

<script>

$(function () {

$('#summernote4').summernote({

        height: 200,

        callbacks: {

            onImageUpload: function(files) {

                for(var i=0; i<files.length; i++){

                    uploadImage(files[i]);

                }

            }

        }

    });

function uploadImage(file){

    var data = new FormData();

    data.append("file", file);

    $.ajax({

        url: 'http://localhost/projectfolder/upload_image.php',

        type: 'POST',

        data: data,

        cache: false,

        contentType: false,

        processData: false,

        success: function(url){

            $('#summernote4').summernote('insertImage', url);

        },

        error: function(){

            alert('Image upload failed.');

        }

    });

}

</script>

2. In the section where you have textarea element id should be summernote4

<textarea name="SOverview" id="summernote4" class="form-control editor"></textarea>

3. Create file upload_image.php and paste this code below

<?php

// upload_image.php

header('Content-Type: text/plain'); // Important!


if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {

    $uploadDir = 'uploads/fromeditor/';

    

    // Create directory if not exists

    if (!file_exists($uploadDir)) {

        mkdir($uploadDir, 0777, true);

    }

    

    $filename = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $_FILES['file']['name']);

    $destination = $uploadDir . $filename;

    

    if (move_uploaded_file($_FILES['file']['tmp_name'], $destination)) {

        // Return only the URL, nothing else

        echo 'http://localhost/trekkingsnepal/' . $destination;

    } else {

        http_response_code(500);

        echo 'Failed to move file';

    }

} else {

    http_response_code(400);

    echo 'No file uploaded';

}

exit; // Make sure nothing else is output

Enjoy now you can upload image from your summernote editor.




Comments