vue3+typescript项目使用tinymce富文本编辑器(图片上传)

默认安装完编辑器只有基本功能,如果还需要上传图片,插入表格之类的功能就需要添加插件如添加上传图片和插入表格的插件

默认安装完编辑器只有基本功能,如果还需要上传图片,插入表格之类的功能就需要添加插件如添加上传图片和插入表格的插件

方法一 加入配置参数images_upload_url

插件提供一个上传地址的参数配置,直接定义这个参数就可以

第一步:引入插件

import 'tinymce/plugins/image'// 插入上传图片插件
import 'tinymce/plugins/media'// 插入视频插件
import 'tinymce/plugins/table'// 插入表格插件

第二步:引入后还需要再plugins上配置和toolbar工具栏上添加相应的按钮

plugins: {
	type: [String, Array],
	default: "lists image media table textcolor wordcount contextmenu",
},
toolbar: {
	type: [String, Array],
	default:"undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image media table | removeformat",
},

第三步:加入配置参数images_upload_url

images_upload_url: '/demo/upimg.php',

如果返回的地址是相对路径,还有一个参数images_upload_base_path,可以给相对路径指定它所相对的基本路径。

images_upload_base_path: '/demo',

后端同学返回给tinymce的JSON数据,形如这样

{ "location": "folder/sub-folder/new-location.png" }

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 = "images/";

  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;
    }
  }

  // Don't attempt to process the upload on an OPTIONS request
  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("Access-Control-Allow-Methods: POST, OPTIONS");
    return;
  }

  reset ($_FILES);
  $temp = current($_FILES);
  if (is_uploaded_file($temp['tmp_name'])){
    /*
      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);

    // Determine the base URL
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https://" : "http://";
    $baseurl = $protocol . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER['REQUEST_URI']), "/") . "/";

    // 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' => $baseurl . $filetowrite));
  } else {
    // Notify editor that the upload failed
    header("HTTP/1.1 500 Server Error");
  }
?>


方法二 加入配置参数images_upload_handler

tinymce.init({
    selector: '.tinymce', language: 'zh_CN',
    mobile: {
        plugins: [
            'a11ychecker', 'advlist', 'advcode', 'advtable', 'autolink', 'checklist', 'export',
            'lists', 'link', 'image', 'charmap', 'preview', 'anchor', 'searchreplace', 'visualblocks',
            'powerpaste', 'fullscreen', 'formatpainter', 'insertdatetime', 'media', 'table', 'help', 'toc', 'wordcount'
        ],
        toolbar:['undo redo | formatpainter casechange blocks  table ' ,
            '| bold italic backcolor | alignleft aligncenter alignright alignjustify code  ',
            'bullist numlist checklist outdent indent | removeformat | a11ycheck  help'],
        images_upload_handler: (blobInfo, success, failure) => {
            var xhr, formData;
            var file = blobInfo.blob();//转化为易于理解的file对象
            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', '/xxxxx');
            xhr.onload = function() {
                var json=JSON.parse(xhr.responseText)
                if (json.code===200){success(json.data)}
                else {failure(json.message)}
            };
            formData = new FormData();
            formData.append('file', file, file.name );//此处与源文档不一样
            xhr.send(formData);
        }
    }
});

这里有一个坑,可能是新版的问题吧,今天配置的时候提示我缺少then?纳了闷不是,官方文档5.0(因为我装的是5.0版本)也是我上面的写法,后来看到官方已经更新了6.0的自定义写法,根据6.0的写法一调整,好了,可能是之前的文档没有更新吧

解决代码如下,要加Promise

const example_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest();
  xhr.withCredentials = false;
  xhr.open('POST', 'postAcceptor.php');

  xhr.upload.onprogress = (e) => {
    progress(e.loaded / e.total * 100);
  };

  xhr.onload = () => {
    if (xhr.status === 403) {
      reject({ message: 'HTTP Error: ' + xhr.status, remove: true });
      return;
    }

    if (xhr.status < 200 || xhr.status >= 300) {
      reject('HTTP Error: ' + xhr.status);
      return;
    }

    const json = JSON.parse(xhr.responseText);

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

    resolve(json.location);
  };

  xhr.onerror = () => {
    reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  };

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

  xhr.send(formData);
});

tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  images_upload_handler: example_image_upload_handler
});

以上这篇vue3+typescript项目使用tinymce富文本编辑器(图片上传)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持芦苇派。

原创文章,作者:ECHO陈文,如若转载,请注明出处:https://www.luweipai.cn/html/1670332196/

  • 1