使用 TinyMCE 编辑器和 ExpressJS 上传本地图片

Fog*_*ggy 5 javascript tinymce image-uploading express

我正在我的网站上运行应用程序,并使用 TinyMCE 编辑器为一些文章和评论运行。完美运行,存储到数据库也可以。但是我需要将本地图像添加到文章中,并且在提交表单时我想将它们保存到服务器上的动态位置(基于我保存的位置)。我什至可以使用 expressJS 和 tinyMce 编辑器来做到这一点吗?

我试过在 tinymce.init 方法中设置需要的东西,我什至在 TinyMce UI 中选择图像时有上传部分,但是一旦我选择图像,我就会收到 HTTP 错误 404。我为解决这个问题所做的是在 express JS 中创建 POST 路由,我想我最终会进入,但我不知道我在做什么。

这是我的 TinyMCE 初始化:

        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);
    }
});
Run Code Online (Sandbox Code Playgroud)

快速路线:

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

php文件:

<?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");
  }
?>
Run Code Online (Sandbox Code Playgroud)

我希望选择一个文件,在 tinyMce 编辑器中查看它,提交保存图像以开始到某个预定义路径。