Upload html file to Tinymce read content and set content of editor - file-upload

I will implement a function that display a file browser where i can upload a html file to read the html documents content and than past this content to editor.
How can i set a toolbar button that opens a file browser, that allows only html file uploads with max file size of 2MB.
Can i read content of file without to save it, like file_get_contents() on php.

I created my own TinyMCE plugin for that.
If you don't know how plugins work, create a new folder named htmlFileImport under the TinyMCE plugins directory. If you are calling tinymce.min.js, then inside this folder create a file named plugin.min.js, otherwise name it plugin.js then paste this code inside
tinymce.PluginManager.add('htmlFileImport', function(editor, url) {
editor.addButton('htmlFileImport', {
text: "Import HTML File",
icon: false,
onclick: function() {
if(editor.getContent() == ""){
editor.showFileDialog();
}
else{
editor.showReplaceContentConfirmDialog();
}
}
});
editor.showReplaceContentConfirmDialog = function(){
eval(editor.dialogConfirmReplaceContentId).Open();
eval(editor.dialogConfirmReplaceContentId).setzIndex(101);
}
editor.showInvalidHtmlFileDialod = function(){
eval(editor.dialogInvalidHtmlFileId).Open();
eval(editor.dialogInvalidHtmlFileId).setzIndex(101);
}
editor.showFileDialog = function(){
var fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
fileSelector.style.display = 'none';
fileSelector.onchange = function(e) {
var file = fileSelector.files[0];
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (event) {
var bodyHtml = event.target.result;
var bodyOpen = bodyHtml.indexOf('<body');
if(bodyOpen == -1)
bodyOpen = bodyHtml.indexOf('< body');
var bodyClose = bodyHtml.indexOf('</body>') + 6;
if(bodyClose == -1)
bodyClose = bodyHtml.indexOf('</ body>') + 7;
if(bodyOpen != -1 && bodyClose != -1){
bodyHtml = bodyHtml.substring(bodyOpen, bodyClose);
var divHtml = document.createElement('div');
divHtml.style.display = 'none';
divHtml.innerHTML = bodyHtml;
editor.setContent(divHtml.innerHTML);
}
else{
editor.showInvalidHtmlFileDialod();
}
}
reader.onerror = function (evt) {
editor.showInvalidHtmlFileDialod();
}
}
};
fileSelector.click();
}
});
dialogConfirmReplaceContentId and dialogInvalidHtmlFileId are custom properties I previously added to my editor in the init function, you will certainly have your own mechanism, but I let this code so you can understand what's going on.
Then to include this new plugin, just add it during your editor's creation by adding the configuration like this:
tinymce.init({
plugins: [
'yourOtherPlugins htmlFileImport'
],
toolbar1: 'yourOtherPlugins htmlFileImport',
.....
});
For allowing only HTML file, you have no way to ensure the user will import this file's type. You can check if file name's extension is .html or .htm or you can do like I did: if I can't find any <body> tag inside then I consider this is not a valid HTML.
You can check the file size by simply calling file.size
You are new on StackOverflow so just to tell you that when you ask a question, you have to show that you tried something and did some research before posting. Here we don't post like if it was a simple Google search. We post question when we are stuck, after trying.

Related

Upload Textarea Content as a file

I want to upload the content of a textarea as a file because content exceed max_input_vars limit in php.ini. In the future maybe it will increase so I prefer to upload it as a file ^^
I show the content to the user in a textarea, so it is editable :) And then click "Save" and send the content of the textarea as a file. How can I do ?
<span onclick="data_save();">Save</span>
<textarea id="textarea">
<?php
print_r($tab);
?>
</textarea>
<script type="text/javascript">
<?php
echo file_get_contents('/var/www/'.$jsdir.'/jquery-2.1.4.min.js');
?>
function data_save()
{
var textToWrite = document.getElementById("textarea").innerHTML;
var textFileAsBlob = new Blob([ textToWrite ], { type: 'text/plain' });
var fileNameToSaveAs = "ecc.plist";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
// Firefox requires the link to be added to the DOM before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
// downloadLink.click();
$.ajax({
url: 'data_save.php',
data: data,
type: 'POST',
success: function(retour)
{
if (retour.indexOf('Oups') != -1)
alert(retour);
},
error: function(obj, text, error)
{
alert("Oups.. " + obj.responseText);
}
});
}
</script>```
It not possible, user must download and the upload the file by himself....

How to preview files before uploaded to server by using file-upload component of vue.js & element-ui?

I'm using vue.js & element-ui to upload files and preview files. I want to preview file(.pdf/.docx/.jpg...) before uploaded to server.
<el-upload
ref="uploadFile"
:on-change="onUploadChange"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
:file-list="fileList"
:http-request="handleUpload"
:data="extendData"
:auto-upload="false"
class="upload-demo"
drag
action="uploadUrl"
multiple>
<i class="el-icon-upload"/>
<div class="el-upload__text">drag here, or <em>click to upload</em></div>
</el-upload>
Only the on-change function can get the content of the file, while the on-preview function only get the meta message. How to get the file content and preview that before which is uploaded to server?
It's not the meta, it's the file. So you need to use a FileReader on the file:
handlePreview(file) {
const reader = new FileReader()
reader.onload = e => console.log(e.target.result) // here is the result you can work with.
reader.readAsText(file)
}
I am also using Element-UI upload box, the following code allow user to import a JSON file to Vue, and preview its content in a new window when clicking the file name. The file is read and stored as object in data during on-change, then
Vue component:
<el-upload class="upload-box" drag action="" :auto-upload="false" :on-change="handleImport" :on-preview="handlePreview" :limit="1" :on-exceed="handleExceed">
<i class="el-icon-upload"></i>
<div class="el-upload__text">Drop file here or <em>click to upload</em></div>
<div class="el-upload__tip" slot="tip">Single JSON file with size less than 500kb</div>
</el-upload>
Script:
export default {
data() {
return {
uploadFile: null,
fileContent: null,
}
},
methods: {
handleImport(file) {
this.uploadFile = file
let reader = new FileReader()
reader.readAsText(this.uploadFile.raw)
reader.onload = async (e) => {
try {
this.fileContent = JSON.parse(e.target.result)
} catch (err) {
console.log(`Load JSON file error: ${err.message}`)
}
}
},
handlePreview() {
let myWindow = window.open();
myWindow.document.write(JSON.stringify(this.fileContent));
myWindow.document.close();
},
handleExceed(files, fileList) {
this.$message.warning(`The limit is 1, you selected ${files.length + fileList.length} totally, please first remove the unwanted file`);
},
},
}

VueJS file upload not accepting file

I'm working on a file upload image preview with VueJS and I'm having an issue where...
1. - file get uploaded by user
2. - preview comes up beside the input field
3. - input field now says there is no image uploaded though there is the preview.
here is the html:
<input type='file' accept='image/*' #change="onChange" name='file' />
<img width='200' :src="uploadPreview" alt='preview' />
here is my vueJs code:
data: function() { return {
uploadPreview : "",
}
},
methods : {
onChange(e) {
if (! e.target.files.length) return;
let file = e.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = e => {
this.uploadPreview = e.target.result; // if this line is commented out or just not present, the upload will work but the preview won't show since uploadPreview does not have a value set.
};
},
}
there's something with that line that I commented in the code there.
this.uploadPreview = e.target.result;
if this line is commented out or just not present, the upload will work but the preview won't show since uploadPreview does not have a value set.
Why is this not working? Why does the input field value for the file reset after simply setting uploadPreview to some binary image data??? Banging my head on this table once more.
I suggest you debugging points. Try and let me know.
data: function() { return {
uploadPreview : "ABCD",
}
},
methods : {
onChange(e) {
if (! e.target.files.length) return;
let file = e.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = e => {
console.log("FIRST SEE WHAT'S INSIDE THE RESULTS",e.target.result);
console.log("SECOND MAKE SURE YOU CAN ACCESS",this.uploadPreview) // this should print ABCD
this.uploadPreview = e.target.result; // if this line is commented out or just not present, the upload will work but the preview won't show since uploadPreview does not have a value set.
};
},
}
and finally
<img width='200' :src="uploadPreview" :alt='uploadPreview' />
(alt should equals to image data)

3.5 Wordpress media uploader manual implementation

I'm having problems to understand how to implement new WP media uploader into my theme options page. Is there a documentation on how to do this or some explanation what-so-ever? I have seen couple of samples of how to do this but none of them has any good explanation about their code. Is there list of options how to customize media uploader frame? I mean wouldn't it be good if you can do something like this (See // Create the media frame.):
// Uploading files
var file_frame;
jQuery('.upload_image_button').live('click', function() {
// If the media frame already exists, reopen it.
if ( file_frame ) {
file_frame.open();
return;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: 'My frame title',
button: {
text: 'My button text',
},
id: 'logo-frame',
multiple: false,
editing_sidebar: false, // Just added for example
default_tab: 'upload', // Just added for example
tabs: 'upload, library', // Just added for example
returned_image_size: 'thumbnail' // Just added for example
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
var attachment;
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
});
// Finally, open the modal
file_frame.open();
return false
});
For WP 3.5, you can use the new media uploader. I'll be brief in the hopes that you know what you're doing. The idea is to call the wp_enqueue_script (this only works on WP >= 3.5 btw). Once the script is called, you can manipulate the javascript object. You'll have to do some inspecting to see your full set of options.
First you have to enqueue the script:
add_action( 'wp_enqueue_scripts', 'front_upload_enqueues' );
function front_upload_enqueues() {
wp_register_script('uploads',
// path to upload script
get_template_directory_uri().'/lib/js/media-upload.js'
);
wp_enqueue_script('uploads');
if ( function_exists('wp_enqueue_media') ) {
// this enqueues all the media upload stuff
wp_enqueue_media();
}
}
Then you have to add the javascript (jQuery in my case):
jQuery(document).ready(function($){
var frame;
/*
* Upload button click event, which builds the choose-from-library frame.
*
*/
$('.form-table').on('click', '.member-upload-field .btn-upload', function( event ) {
var $el = $(this);
event.preventDefault();
// Create the media frame.
frame = wp.media.frames.customHeader = wp.media({
title: $el.data('choose'),
library: { // remove these to show all
type: 'image', // specific mime
author: userSettings.uid // specific user-posted attachment
},
button: {
text: $el.data('update'), // button text
close: true // whether click closes
}
});
// When an image is selected, run a callback.
frame.on( 'select', function() {
// Grab the selected attachment.
var attachment = frame.state().get('selection').first(),
link = $el.data('updateLink');
$el.prev('input').val( attachment.attributes.id );
$el.parent().prev().find('img').attr('src', attachment.attributes.url );
});
frame.open();
});
});

making safari extension in context menu. When over image mouse right click, how i know image url?

Making safari extension imageSearch By google.
Here is my source.
injected.js
document.addEventListener("contextmenu", handleContextMenu, false);
function handleContextMenu(event) {
safari.self.tab.setContextMenuEventUserInfo(event, event.target.nodeName);
}
global.html
<!DOCTYPE HTML>
<script type="text/javascript" src="jquery.js"></script>
<script>
safari.application.addEventListener("contextmenu", handleContextMenu, false);
function handleContextMenu(event) {
var query = event.userInfo;
if (query === "IMG") {
event.contextMenu.appendContextMenuItem("imageSearch", "Search Google with this image");
}
}
safari.application.addEventListener("command", performCommand, false);
function performCommand(event) {
if (event.command === "imageSearch") {
/*How I get image Url??? */
var imageUrl="";
/*
var url = "http://images.google.com/searchbyimage?image_url="+imageUrl;
var tab = safari.application.activeBrowserWindow.openTab("foreground");
tab.url = url;
*/
}
}
My goal is..
if mouse rightclick add "Search by Google With This Image" int the context menu. (clear)
and click "Search by Google With This Image" google it. (???)
so i want to know image url.
What should I do?
You could try this:
store the whole node into the event's userInfo:
function handleContextMenu(event) {
safari.self.tab.setContextMenuEventUserInfo(event, event.target);
}
add some global javascript variable to your global.html (e.g. var lastClickedImg),
change your handleContextMenu function to store the event.userInfo in function handleContextMenu to this variable:
function handleContextMenu(event) {
var query = event.userInfo;
if (query.nodeName === "IMG") {
lastClickedImg = query;
event.contextMenu.appendContextMenuItem("imageSearch", "Search Google with this image");
}
}
in your function performCommand you will easily get the image's url from lastClickedImg:
lastClickedImg.src
You can find image URL by placing an event listener for contextmenu in an injected script.
function contextMenuHandler(event)
{
var url = event.target.src;
safari.self.tab.setContextMenuEventUserInfo(event, url);
}
document.body.addEventListener("contextmenu", contextMenuHandler, false);
And then recovering the image src in command event
var imageUrl = event.userInfo;
You should also do some validation to make sure it's an image.