Ir al contenido principal

Destacado

Desarrollo web Bootcamp

  Introducción a la Programación La programación es el proceso de diseñar y escribir instrucciones que las computadoras entienden para realizar tareas específicas. Estas instrucciones se conocen como código , y permiten a los desarrolladores crear aplicaciones, sitios web, juegos y mucho más. Lenguajes de Programación Comunes en el Desarrollo Web En el desarrollo web, los lenguajes más utilizados incluyen: HTML : Define la estructura del contenido en una página web. CSS : Estiliza y da diseño a los elementos de HTML. JavaScript : Agrega interactividad y funcionalidades dinámicas a las páginas web.      PHP y Python : Son lenguajes de servidor para manejar la lógica y los datos. SQL : Sirve para gestionar bases de datos. Sintaxis Básica La sintaxis es un conjunto de reglas que determina cómo escribir código en un lenguaje específico. Es fundamental para que el programa funcione correctamente. Por ejemplo: javascript let mensaje = "¡Hola Mundo!" ; console . log (mens...

Ckeditor subiendo imágenes

Ckeditor subiendo imágenes

 En la siguiente entrada podremos subir imagenes en ckeditor https://ckeditor.com/ckeditor-4/

ckeditor es un complemento que nos permite insertar html .
Es muy fácil y sencillo obtener el html de este complemento, la integración consiste en colocar el complemento en un textarea y mandar a llamarlo para que el text area tome los diseños colocandolo de la siguiente manera.


En el siguiente código mandamos a llamar el complemento   <script src="https://cdn.ckeditor.com/4.14.1/standard-all/ckeditor.js"></script>


<!doctype html>

<html lang="en">


<head>

  <meta charset="utf-8">

  <meta name="robots" content="noindex, nofollow">

  <title>Complemento Ckeditor</title>

  <script src="https://cdn.ckeditor.com/4.14.1/standard-all/ckeditor.js"></script>

</head>


<body>

  <textarea cols="80" id="editor1" name="editor1" rows="10" data-sample-short>&lt;p&gt;This is some &lt;strong&gt;sample text&lt;/strong&gt;. You are using &lt;a href=&quot;https://ckeditor.com/&quot;&gt;CKEditor&lt;/a&gt;.&lt;/p&gt;</textarea>

    //hacemos las siguientes configuraciones 

  <script>

    CKEDITOR.addCss('.cke_editable { font-size: 15px; padding: 2em; }');


    CKEDITOR.replace('editor1', {

      toolbar: [{

          name: 'document',

          items: ['Print']

        },

        {

          name: 'clipboard',

          items: ['Undo', 'Redo']

        },

        {

          name: 'styles',

          items: ['Format', 'Font', 'FontSize']

        },

        {

          name: 'colors',

          items: ['TextColor', 'BGColor']

        },

        {

          name: 'align',

          items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']

        },

        '/',

        {

          name: 'basicstyles',

          items: ['Bold', 'Italic', 'Underline', 'Strike', 'RemoveFormat', 'CopyFormatting']

        },

        {

          name: 'links',

          items: ['Link', 'Unlink']

        },

        {

          name: 'paragraph',

          items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote']

        },

        {

          name: 'insert',

          items: ['Image', 'Table']

        },

        {

          name: 'tools',

          items: ['Maximize']

        },

        {

          name: 'editing',

          items: ['Scayt']

        }

      ],


      extraAllowedContent: 'h3{clear};h2{line-height};h2 h3{margin-left,margin-top}',


      // Adding drag and drop image upload.

      extraPlugins: 'print,format,font,colorbutton,justify,uploadimage',

     // uploadUrl: '/apps/ckfinder/3.4.5/core/connector/php/connector.php?command=QuickUpload&type=Files&responseType=json',


      // Configure your file manager integration. This example uses CKFinder 3 for PHP.

      filebrowserBrowseUrl: 'kcfinder-master/browse.php?opener=ckeditor&type=files',

      filebrowserImageBrowseUrl: 'kcfinder-master/browse.php?opener=ckeditor&type=images',

      filebrowserUploadUrl: 'upload.php',

      filebrowserImageUploadUrl: 'upload.php',


      height: 560,


      removeDialogTabs: 'image:advanced;link:advanced'

    });

  </script>

</body>


</html>


Se debería de ver de la siguiente manera :


Ahora vamos agregar un complemento mas kcfinfer 
Este complemento nos permitirá subir imagenes de una manera fácil

      filebrowserImageBrowseUrl: 'kcfinder-master/browse.php?opener=ckeditor&type=images',



Solamente descargamos kcfinder-master desde github
y lo integramos colocandolo en nuestro directorio 

Es muy importante configurar un archivo para la subida de imágenes en el ckeditor 

      filebrowserImageUploadUrl: 'upload.php',

Colocamos el siguiente código 

$basePath = "/imagenes/";

// Step 3: Put here the Url that should be used for the upload folder (it the URL to access the folder that you have set in $basePath
// you can use a relative url "/images/", or a path including the host "http://example.com/images/"
// ALWAYS put the final slash (/)
$baseUrl = "/imagenes/";

// Done. Now test it!



// No need to modify anything below this line
//----------------------------------------------------

// ------------------------
// Input parameters: optional means that you can ignore it, and required means that you
// must use it to provide the data back to CKEditor.
// ------------------------

// Optional: instance name (might be used to adjust the server folders for example)
$CKEditor = $_GET['CKEditor'] ;

// Required: Function number as indicated by CKEditor.
$funcNum = $_GET['CKEditorFuncNum'] ;

// Optional: To provide localized messages
$langCode = $_GET['langCode'] ;

// ------------------------
// Data processing
// ------------------------

// The returned url of the uploaded file
$url = '' ;

// Optional message to show to the user (file renamed, invalid file, not authenticated...)
$message = '';

if(isset($_FILES["upload"]["type"]))
        {
            $validextensions = array("jpeg", "jpg", "png");
            $temporary = explode(".", $_FILES["upload"]["name"]);
            $file_extension = end($temporary);
            if ((($_FILES["upload"]["type"] == "image/png") || ($_FILES["upload"]["type"] == "image/jpg") || ($_FILES["upload"]["type"] == "image/jpeg")
) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) {
                if ($_FILES["upload"]["error"] > 0)
                {
                    echo "Return Code: " . $_FILES["upload"]["error"] . "<br/><br/>";
                }
                else
                {
                    if (file_exists("imagenes/".$_FILES["upload"]["name"])) {
                        echo $_FILES["upload"]["name"] . " <span id='invalid'><b>Archivo ya existe.</b></span> ";
                    }
                    else
                    {
                $sourcePath = $_FILES['upload']['tmp_name']; // Storing source path of the file in a variable
                $targetPath = "imagenes/".$_FILES['upload']['name']; // Target path where file is to be stored
                move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file


               


                $result= 1;
               $message="Se agrego imagen";

                }
                }




                }
            else
            {
                $result=2;
                $message="No se agrego imagen";
            }

    }
// ------------------------
// Write output
// ------------------------
// We are in an iframe, so we must talk to the object in window.parent
$respuesta['respuesta']=$result;
echo json_decode($respuesta);

?>


Después de estas sencillas configuraciones nosotros podremos subir de una forma fácil y simple imágenes desde Ckeditor








Comentarios

Entradas populares