Skip to content

Instantly share code, notes, and snippets.

@tacone
Created June 23, 2016 10:53
Show Gist options
  • Save tacone/7fd9bf886b099c6eaad6d5ba63aa676c to your computer and use it in GitHub Desktop.
Save tacone/7fd9bf886b099c6eaad6d5ba63aa676c to your computer and use it in GitHub Desktop.
TinyMce with file upload
$(function () {
var editorCount = 0;
$('.richtext').each(function () {
var sendFile = function (callback) {
data = new FormData();
data.append("file", fileInput[0].files[0]);
$.ajax({
url: "/upload/image",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
callback(data.filename);
},
error: function (jqXHR, textStatus, errorThrown) {
try {
var message = JSON.parse(jqXHR.responseText).file[0];
message = message.replace(/^[a-z]/, function (letter) {
return letter.toUpperCase();
});
alert(message);
} catch (e) {
alert('Whoops');
}
}
});
};
editorCount++;
var textarea = $(this);
var editorId = editorCount;
var uploadCallback;
textarea.attr('data-editor-id', editorId);
var form = $(
'<form method="post" enctype="multipart/form-data" style="width:0;height:0;overflow:hidden">' +
'<input name="file" type="file">' +
'</form>'
);
$('body').append(form);
var fileInput = form.find('input').first();
fileInput.change(function () {
sendFile(uploadCallback);
});
tinymce.init({
selector: '[data-editor-id=' + editorId + ']',
height: 500,
theme: 'modern',
plugins: [
'autolink lists link image hr anchor',
'wordcount visualblocks code fullscreen',
'insertdatetime media nonbreaking table contextmenu',
'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_advtab: true,
content_css: [
$('.main-css').attr('href')
],
file_browser_callback_types: 'image',
file_picker_callback: function (callback, value, meta) {
// Provide image and alt text for the image dialog
if (meta.filetype == 'image') {
fileInput.click();
uploadCallback = callback;
}
/* --- left as an example --
// Provide file and text for the link dialog
if (meta.filetype == 'file') {
callback('mypage.html', {text: 'My text'});
}
// Provide alternative source and posted for the media dialog
if (meta.filetype == 'media') {
callback('movie.mp4', {source2: 'alt.ogg', poster: 'image.jpg'});
}
*/
},
relative_urls: false,
remove_script_host: true
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment