对于需要为客户端进行修改的项目,我在表单内实现了TinyMCE编辑器实例。客户的要求是拥有一个简单的系统来保存一些投资组合数据,例如客户名称,客户徽标以及客户项目的简短说明。我没有编写原始代码,但发现了一种灾难。我以前从未使用过tinyMCE编辑器,我已经开始阅读文档,并且与最初编写代码的人相比,它似乎配置不错。问题是我只想使用一种表单来管理所有请求的字段,但是现在有不同的表单。我尝试将所有字段放在一种表单中,但是它将停止工作,并且数据和徽标未保存到数据库/已上传。这是代码,我该如何实现?
HTML代码:
<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代码:
$(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");
}
?>
另一个问题是有关将内容可视化到前端的问题。我知道tinyMCE是wordpress的默认编辑器,对于前端,我想显示内容的预览,而不是全部,我该怎么做?