duanbo1659 2018-10-11 08:45
浏览 537

使用一个表单管理TinyMCE编辑器和文本输入文件上传

For a project that I need to modify for a client, I have a TinyMCE editor instance implemented inside a form. The client request is to have a simple system to save some portfolio data, like his clients name,clients logo and then a brief description of the clients projects. I didn't write the original code, and I've found a sort of disaster. I never used the tinyMCE editor before, I've started reading the documentations and It's seems well configured from the person who originally wrote the code. The problem is that I want to use just one form to manage all the requested field, but now there are different forms. I've tried to put all the fields inside one form but It will stop working and the data and the logo are not saved to the database / uploaded. Here is the code, how i can achieve this?

HTML code:

<div class="container" id="editor">
  <div class="row">
    <div id="step-1" class="col-sm-12 col-md-12 col-lg-12">
      <form method="POST" action="" enctype="multipart/form-data" id="imageForm">
        <div class="form-row">
          <div class="col-sm-12 col-md-3 col-lg-3">
            <input type="text" class="form-control" name="client_name" id="clientName" placeholder="Client name">
          </div>

          <div class="col-sm-12 col-md-3 col-lg-3">
            <div class="custom-file">
              <input type="file" name="client_logo" class="custom-file-input" id="clientLogo">
              <label class="custom-file-label" for="clientLogo">Client logo</label>
            </div>
          </div>

          <div class="col-sm-12 col-md-6 col-lg-6" id="imagePreview">
            <img class="card-img-top" id="prvImage" src="" alt="Preview logo">
          </div>
        </div>
            <button type="submit" class="btn btn-primary btn-submit">Carica</button>
      </form>
    </div>

    <div id="step-2" class="col-sm-12 col-md-12 col-lg-12">
      <form method="POST" action="" id="editorForm">
        <textarea class="form-control" name="post_content" id="postContent"></textarea>
      </form>
    </div>
  </div>
</div>

JS code:

$(document).ready(function(){

editor();
imageLogoHandler();
imgPreviewHandler();

});

var imageLogoHandler = function(){
    $('.btn-submit').on('click' , function(e){
      e.preventDefault();
      alert('Upload in progress');
          var data = new FormData();
          data.append('client_logo', $('#clientLogo').get(0).files[0]);
          data.append('client_name', $('#clientName[name="client_name"]').val());
          data.append('action', 'upimg');

          $.ajax({
            type: 'POST',
             url: 'PostHandler.php',
             data: data,
             processData: false,
             contentType: false,
             cache: false,
             success: function(res){

             }
          });
    });
}

var imgPreviewHandler = function(){
  document.getElementById('clientLogo').onchange = function (evt) {
    var tgt = evt.target || window.event.srcElement,
        files = tgt.files;
    if (FileReader && files && files.length) {
        var fr = new FileReader();
        fr.onload = function () {
            document.getElementById('prvImage').src = fr.result;
        }
        fr.readAsDataURL(files[0]);
      }
    }
}

var editor = function(){
  tinymce.init({
    selector: '#postContent',
    height: 380,
    plugins: 'save print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern help',
    toolbar: 'save | formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat | image',
    relative_urls : false,
    remove_script_host : false,
    convert_urls: true,
    images_upload_url: 'ImageHandler.php',
    automatic_uploads: false,
    save_onsavecallback: function(){
          var action = 'savePost';
          var data = tinymce.get('postContent').getContent();
          $.ajax({
            type: 'POST',
            url: 'PostHandler.php',
            data: {action: action, post_content: data},
            cache: false,
            success: function(response){
              alert(response);
            }
      });
    }
  });
}

PHP

<?php
// PostHandler.php
session_start();

require_once dirname(__DIR__, 1).'/Config.php';

if(isset($_POST['action']) && $_POST['action'] === 'upimg'){

  if(is_uploaded_file($_FILES['client_logo']['tmp_name'])){

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

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

  $clientName = filter_var($_POST['client_name'], FILTER_SANITIZE_STRING);

  $_SESSION['client_name'] = $clientName;

  $imageFolder = '../../img/portfolio/';

  $file = $imageFolder . $_FILES['client_logo']['name'];

  move_uploaded_file($_FILES['client_logo']['tmp_name'], $file);

  $stmt = $db->prepare('INSERT INTO portfolio (client_name, client_logo) VALUES (?, ?)');
    if($stmt->execute(array($clientName, $file))){
      echo '';
    } else {
      echo '';
    }
  }

}
elseif(isset($_POST['action']) && $_POST['action'] === 'savePost'){

  $postContent = $_POST['post_content'];

  $stmt = $db->prepare('UPDATE portfolio SET post_content = ? WHERE client_name = ?');
    if($stmt->execute(array($postContent, $_SESSION['client_name']))){
      echo '';
    } else {
      echo '';
    }

}

?>

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

  /*********************************************
   * Change this line to set the upload folder *
   *********************************************/
  $imageFolder = "../../img/portfolio/";

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

    // if(!file_exists($_POST['client_name'])){
    //   $clientFolder = mkdir($imageFolder.$_POST['client_name'], 0777);
    // }

    // Accept upload if there was no origin, or if it is an accepted origin
    //$filetowrite = $imageFolder . $temp['name'];
    $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");
  }

?>

Another question is about the visualization of the contents to the front-end. I know that tinyMCE is the default editor of wordpress, and for the front-end I want to display a preview of the contents and not all of it, how I can do this?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
    • ¥15 谁有desed数据集呀
    • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
    • ¥15 关于#hadoop#的问题
    • ¥15 (标签-Python|关键词-socket)