Insert/upload image to tinyMCE 4.X - javascript

I want to add feature to my tinyMCE 4.X. It is file uploader. I'm trying to do it many ways, but no one worked. I'm using this code:
tinymce.init({
selector: "textarea[name=obsah], textarea[name=perex]",
theme: "modern",
paste_data_images: true,
plugins: [
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table contextmenu directionality",
"emoticons template paste textcolor colorpicker textpattern"
],
toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
toolbar2: "print preview media | forecolor backcolor emoticons",
image_title: true,
automatic_uploads: true,
images_upload_url: '/admin',
file_picker_types: 'image',
file_picker_callback: function(cb, value, meta) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.onchange = function() {
var file = this.files[0];
var id = 'blobid' + (new Date()).getTime();
var blobCache = tinymce.activeEditor.editorUpload.blobCache;
var blobInfo = blobCache.create(id, file);
blobCache.add(blobInfo);
cb(blobInfo.blobUri(), { title: file.name });
};
input.click();
},
});
After I choose the image, it shows in the area, that is OK, but when I click submit, $_POST and $_FILES are empty and console is talking about error in JSON unexpected error. Can you help me please? How to send multiple images ?
Thank you

You can use the following code to upload image using tinyMCE 4.x as suggested by its documentation.
https://www.tinymce.com/docs/configure/file-image-upload/
tinymce.init({
selector: 'textarea', // change this value according to your HTML
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'postAcceptor.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);
}
});
To use this code you just need to create postAcceptor.php file pn your server. Here is the link of postAcceptor.php
https://www.tinymce.com/docs/advanced/php-upload-handler/
<?php
/*******************************************************
* Only these origins will be 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/";
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.0 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.0 500 Invalid file name.");
return;
}
// Verify extension
if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
header("HTTP/1.0 500 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.0 500 Server Error");
}
?>

Related

Get 500 error when i try to load my website with TinyMCE image upload enabled

So everything works fine on locahost on my xampp appache server, but when i move everything to the domain website i get the GET 500 error. i cant click buttons on website and my Database doesn't load... I am hosting domain on some provider.
Error in chrome
Error in chrome
And i checked the logs and couldn't find anything.
Here is my code:
//TINYMCE EDITOR
tinymce.init({
selector: '#mytextarea', //ID textareea
plugins: [
'advlist autolink link image lists charmap print preview hr anchor pagebreak',
'searchreplace wordcount visualblocks code fullscreen insertdatetime media nonbreaking',
'table emoticons template paste help'
],
toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' + //VSE KA BO V EDITORJU
'bullist numlist outdent indent | link image | print preview media fullscreen | ' +
'forecolor backcolor emoticons | help',
menu: {
favs: {
title: 'My Favorites',
items: 'code visualaid | searchreplace | emoticons'
}
},
menubar: 'favs file edit view insert format tools table help',
content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }',
paste_data_images: true, //Da lahko slike drag and drop
mobile: { //ZdruÅūljivo z telefonom
menubar: true
},
entity_encoding : "raw",
images_upload_url: 'postAcceptor.php',
//automatic_uploads: false,
images_upload_base_path: 'img/',
images_upload_handler: function(blobInfo, success, failure){
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'postAcceptor.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);
}
});
<?php
// Allowed origins to upload images
$accepted_origins = array("www.mydomain.com", "http://localhost");
// Images upload path
$imageFolder = "img/";
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;
}
}
// 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.
echo json_encode(array('location' => $filetowrite));
} else {
// Notify editor that the upload failed
header("HTTP/1.1 500 Server Error");
}
?>

Uncaught SyntaxError: Unexpected token < in JSON at position 0 with TinyMCE Editor Image Upload

So I am working on a blog CMS and I am trying give my TinyMCE WYSIWYG editor the ability to upload images when a user is creating a post. I'm using the actual code from the TinyMCE Docs (https://www.tiny.cloud/docs/general-configuration-guide/upload-images/), but when I attempt to upload an image, it gets stuck loading and gives an error "Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.xhr.onload". Any ideas on what may be causing this? I've seen a few questions about this online, but they all seem to involve jQuery which I am not using. And sorry if this is too much of a question. Thanks for your time.
JavaScript (Top of body)
<script>
function example_image_upload_handler (blobInfo, success, failure, progress) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'upload.php');
xhr.upload.onprogress = function (e) {
progress(e.loaded / e.total * 100);
};
xhr.onload = function() {
var json;
if (xhr.status === 403) {
failure('HTTP Error: ' + xhr.status, { remove: true });
return;
}
if (xhr.status < 200 || xhr.status >= 300) {
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);
};
xhr.onerror = function () {
failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
};
tinymce.init({
selector: '#tinymce',
height: 450,
plugins: [
'advlist autolink link image lists charmap print preview hr anchor pagebreak',
'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
'table emoticons template paste help'
],
toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' +
'bullist numlist outdent indent | link image | print preview media fullpage | ' +
'forecolor backcolor emoticons | help',
menu: {
favs: {title: 'My Favorites', items: 'code visualaid | searchreplace | emoticons'}
},
menubar: 'favs file edit view insert format tools table help',
content_css: 'css/content.css',
images_upload_handler: example_image_upload_handler
});
</script>
PHP (upload.php)
<?php
$accepted_origins = array("http://localhost");
$imageFolder = "post-img/";
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");
}
?>
Thanks for the replies... It turns out I just needed the JS, PHP, and the upload folder to all be in the same folder. Once I did that, it worked no problem. The code was good.
Your json is returning html which is start with < tag instead of json response there. May be server error occurred.

Local image upload using TinyMCE editor and ExpressJS

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.

Tinimce 4 image upload throwing HTTP Error: 404

I'm using tinymce 4 with image upload from example and after selecting picture to upload I'm getting "HTTP Error: 404" message.
I've tested example postAcceptor.php with posting image file and it works.
On result of posting image I'm getting that JSON response:
{"location":"/home/mylogin/domains/mydomain.com/public_html/projects/projectname/img/gallery/422.jpg"}
Is that correct with those extra slashes?
My code for init:
tinymce.init({
selector: 'textarea.content',
plugins: 'image code',
toolbar: 'undo redo | link image | code',
// enable title field in the Image dialog
image_title: true,
automatic_uploads: true,
images_upload_url: 'postAcceptor.php',
images_upload_base_path: '/img/gallery/',
images_upload_credentials: true,
file_picker_types: 'image',
// and here's our custom image picker
file_picker_callback: function(cb, value, meta) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
var id = 'blobid' + (new Date()).getTime();
var blobCache = tinymce.activeEditor.editorUpload.blobCache;
var base64 = reader.result.split(',')[1];
var blobInfo = blobCache.create(id, file, base64);
blobCache.add(blobInfo);
cb(blobInfo.blobUri(), { title: file.name });
};
};
input.click();
}
});
The JSON you are returning sure looks like the location on the server's hard drive. The location gets turned into the src attribute for the image so it needs to be the URL that would allow the browser to fetch the image via the web server.
404 was caused because of
images_upload_url: 'postAcceptor.php',
I've changed it to
images_upload_url: './js/tinymce/postAcceptor.php',
Worked like a charm..

jQuery - Downloading Textarea Contents

How can I download the textarea value/contents when I click a button? It should act like PHP:
<?php
$file = 'proxies.txt';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
I just can't find any way on here to do it. I don't want it to make a href to click a second time to download. I just want to click a button and it will download a txt file containing the textarea's contents.
My current code that wont work:
$('#test').click(function() {
contentType = 'data:application/octet-stream,';
uriContent = contentType + encodeURIComponent($('#proxiescontainer').val());
$(this).setAttribute('href', uriContent);
});
Explanation:
#test is the a tag wrapping the button;
#proxiescontainer is the textarea itself;
So how can I get it to be a onClick download of the textarea's contents?
My AJAX:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "grab.php", true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var t = $('#proxiescontainer').scrollTop(), $d2 = $('#proxiescontainer').replaceWith('<button type="button" id="download" class="form-control button">Download</button><textarea id="proxiescontainer" class="form-control message-input" style="height: 250px!important;">' + xhttp.responseText + '</textarea>');
if (t){ $('#proxiescontainer').scrollTop(t + $d2.outerHeight()); }
}
}
Using existing js setAttribute() is not a jQuery method ; to use on DOM element remove jQuery() wrapper
$('#test').click(function() {
contentType = 'data:application/octet-stream,';
uriContent = contentType + encodeURIComponent($('#proxiescontainer').val());
this.setAttribute('href', uriContent);
});
alternatively using Blob createObjectURL() , download attribute
$("button").click(function() {
// create `a` element
$("<a />", {
// if supported , set name of file
download: $.now() + ".txt",
// set `href` to `objectURL` of `Blob` of `textarea` value
href: URL.createObjectURL(
new Blob([$("textarea").val()], {
type: "text/plain"
}))
})
// append `a` element to `body`
// call `click` on `DOM` element `a`
.appendTo("body")[0].click();
// remove appended `a` element after "Save File" dialog,
// `window` regains `focus`
$(window).one("focus", function() {
$("a").last().remove()
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea></textarea>
<button>download</button>

Categories

Resources