Local image upload using TinyMCE editor and ExpressJS
Asked Answered
A

0

6

I'm running application on my website and for some articles and reviews im using TinyMCE editor. Works perfectly, storing to DB also works. But i have a need to add local images to articles and upon submitting a form i want to save them to dynamic location on server (based from where i save). Can i even do this using expressJS and tinyMce editor?

I've tried setting needed stuff in tinymce.init method, I even have upload section when selecting Image in TinyMce UI, but as soon as i select image, i'm getting HTTP error 404. What i did to solve this, is to create POST route in express JS where i suppose i end up in, but i have no idea what i'm doing.

This is my TinyMCE init:

        tinymce.init({
        selector: '#tinySelector',
        plugins: 'advlist autolink link code image lists charmap print preview textcolor media',
        toolbar: 'undo redo | image code',
        relative_urls: true,
        document_base_url: 'http://www.example.com/',
        images_upload_url: '/upload.php',
        images_upload_hand: function (blobInfo, success, failure) {
        var xhr, formData;

        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', '/upload.php');

        xhr.onload = function () {
            var json;

            if (xhr.status != 200) {
                failure('HTTP Error: ' + xhr.status);
                return;
            }

            json = JSON.parse(xhr.responseText);

            if (!json || typeof json.location != 'string') {
                failure('Invalid JSON: ' + xhr.responseText);
                return;
            }

            success(json.location);
        };

        formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());

        xhr.send(formData);
    }
});

Express route:

router.post('/upload.php', ensureAuthenticated, (req, res) => {
    console.log('testis');
});

Php file:

<?php
  /***************************************************
   * Only these origins are allowed to upload images *
   ***************************************************/
  $accepted_origins = array("http://localhost", "http://192.168.1.1", "http://example.com");

  /*********************************************
   * Change this line to set the upload folder *
   *********************************************/
  $imageFolder = "/public/tinyImages/";

  reset ($_FILES);
  $temp = current($_FILES);
  if (is_uploaded_file($temp['tmp_name'])){
    if (isset($_SERVER['HTTP_ORIGIN'])) {
      // same-origin requests won't set an origin. If the origin is set, it must be valid.
      if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
        header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
      } else {
        header("HTTP/1.1 403 Origin Denied");
        return;
      }
    }

    /*
      If your script needs to receive cookies, set images_upload_credentials : true in
      the configuration and enable the following two headers.
    */
    // header('Access-Control-Allow-Credentials: true');
    // header('P3P: CP="There is no P3P policy."');

    // Sanitize input
    if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
        header("HTTP/1.1 400 Invalid file name.");
        return;
    }

    // Verify extension
    if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
        header("HTTP/1.1 400 Invalid extension.");
        return;
    }

    // Accept upload if there was no origin, or if it is an accepted origin
    $filetowrite = $imageFolder . $temp['name'];
    move_uploaded_file($temp['tmp_name'], $filetowrite);

    // Respond to the successful upload with JSON.
    // Use a location key to specify the path to the saved image resource.
    // { location : '/your/uploaded/image/file'}
    echo json_encode(array('location' => $filetowrite));
  } else {
    // Notify editor that the upload failed
    header("HTTP/1.1 500 Server Error");
  }
?>

I expect to select a file, see it in tinyMce editor, upon submitting saving image for start to some predefined path.

Apophyge answered 18/8, 2019 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.