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....
Related
I'm having a hard time getting anything to work with this the way I need it, but I have a working dropzone instance in my Vue project.
I can upload the image and call functions within the dropzone code, however, I need to call a function directly from the form in the html in order to send the 'card' object.
All I need to do is call a function when a file is added through the dropzone form, with the filename.
My code:
<div class="uk-width-3-10">
<form v-on:change="imageChange(card)" method="post" action="{{url('product/parts/upload/store')}}" enctype="multipart/form-data"
class="dropzone" v-bind:id="'dropzone-'+i">
</form>
</div>
...
imageChange(Card){
console.log('working');
},
addCard(){
Vue.nextTick(function () {
new Dropzone("#dropzone-"+cardIndex, {
maxFilesize: 12,
renameFile: function (file) {
var dt = new Date();
var time = dt.getTime();
return time + file.name;
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 50000,
removedfile: function (file) {
console.log(file.upload.filename);
var name = file.upload.filename;
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
},
init: function() {
this.on("addedfile",
function(file) {
instance.imageZoneNames.push({name: file.upload.filename});
console.log(file);
console.log(instance.imageZoneNames);
});
}
});
});
}
Dropzone has many events, You used removedfile() event! there is another event called addedfile() and executes when a file is added to the dropzone list
imageChange(card) {
console.log(card)
},
addCard() {
Vue.nextTick(() => {
new Dropzone('#dropzone-` + cardIndex, {
addedfile(file) {
this.imageChange(file);
}
}
}
}
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`);
},
},
}
I have written a functionality where I want to upload a form without using any forms whatsoever, I am calling an ajax event on change event of input type=file with id, I am getting the $_FILES data in ajax file 'upload.php' using POST method using jQuery. The input tag is not inside any form tag. It stands individually. Below is my code:
my plain html input type='file' without form:
<div class="profile_pic">
<img id="upload-button" class="profile-pic img-circle profile_img" src="img/default-image.png" alt="default">
<input class="file-upload" type="file" name="profile_pic" id="profile_pic" />
</div>
My Javascript code is:
var readURL = function(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#upload-button').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".file-upload").on('change', function(){
readURL(this);
alert('working');
var file = profile_pic.files[0];
var formData = new FormData();
formData.append('formData', file);
$.ajax({
url: "uploadFile.php",
type: "POST",
processData: false,
contentType: false,
dataType : 'json',
data: formData,
success: function (data) {
alert(data);
}
});
});
$("#upload-button").on('click', function() {
$(".file-upload").click();
});
UploadFile.php code below:
<?php
print_r($_FILES);
?>
the following file data Am getting in alert :
Array
(
[formData] => Array
(
[name]=> Tulips.jpg
[type]=> image/jpeg
[tmp_name]=> chroot/tmp/phpipdF97
[error]=> 0
[size]=> 620888
)
)
how can I access those file data inorder to upload file to a destination folder path using php's move_uploaded_file()? Thanks in advance.
I got the solution. I have accessed the $_FILES values in "uploadFile.php" like below:
$_FILES["formData"]["tmp_name"]
$_FILES["formData"]["name"]
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.
I'm using dojo's event delegation to connect a Tooltip widget to dynamically generated dom nodes.
The Dojo site explains event delegation this way:
"The idea behind event delegation is that instead of attaching a
listener to an event on each individual node of interest, you attach a
single listener to a node at a higher level, which will check the
target of events it catches to see whether they bubbled from an actual
node of interest; if so, the handler's logic will be performed."
Following is my code implementation. It works beautifully ... EXCEPT, the tooltip only shows AFTER the first mouse over event. When I first mouseover the node, the event fires perfectly, but the tooltip doesn't render. It will only show the consequent mouseover events. On the first mouseover event, I can watch the Firebug console and see the xhr.get go to the database and get the correct data. If I comment out the tooltip and throw in a simple alert(), it works the first time.
Any suggestions on how to get the Tooltip to show on the first mouseover event? Thanks in advance!
<div class="col_section" id="my_groups">
<div class="col_section_label">My Groups</div>
<ul>
<?php
foreach($myGroups as $grp) {
echo '<li><a class="myGroupLink" id="grp'.$grp['grp_id'].'">'.$grp['name'].'</a></li>';
}
?>
</ul>
</div>
<script>
require(["dojo/on",
"dojo/dom",
"dijit/Tooltip",
"dojo/_base/xhr",
"ready!"], function(on, dom, Tooltip, xhr) {
// Get Group ToolTip
var myObject = {
id: "myObject",
onMouseover: function(evt){
var grp_id = this.id;
var content = '';
xhr.get({
url: "getGrpInfo.php",
handleAs: "json",
content: {
grp_id: grp_id,
content: "tooltip"
},
load: function(info) {
if(info == 0) {
content = '<div class="grpToolTip">';
content += ' Information about this group is confidential';
content += '</div>';
} else {
content = '<div class="grpToolTip">';
content += ' <img src="../ajax/getimg.php?id='+info.logo_id+'" />';
content += ' <div style="text-align:center">'+info.name+'</div>';
content += '</div>';
}
new Tooltip({
connectId: [grp_id],
label: content
});
},
error: function() {}
});
}
};
var div = dom.byId("my_groups");
on(div,".myGroupLink:mouseover",myObject.onMouseover);
});
</script>
Your Tooltip does not show on the first onmouseover because it does not exist at the moment the onmouseover event was fired.
dijit/Tooltip instances manage theirs mouse events themselves, so you do not have to manage onmouseover/onmouseout and you probably did so because you do not want to preload data or you want to load data every time the tooltip is about to show.
Beside dijit/Tooltip instances you can use Tooltip.show(innerHTML, aroundNode, position) and Tooltip.hide(aroundNode) to display tooltips, but in that case you will have to manage mouse events yourself, which is what you need, because from the UX perspective, you do not want to show single tooltip, you want to:
Show a tooltip indicating information is being loaded.
Then either:
display XHR loaded information if a user still hover over the node
cancel XHR and hide tooltip on mouseout
Here is working example: http://jsfiddle.net/phusick/3hmds/
require([
"dojo/dom",
"dojo/on",
"dojo/_base/xhr",
"dijit/Tooltip",
"dojo/domReady!"
], function(
dom,
on,
xhr,
Tooltip
) {
on(dom.byId("groups"), ".group-link:mouseover", function(e) {
var target = e.target;
Tooltip.show("Loading...", target);
var def = xhr.post({
url: "/echo/html/",
content: { html: target.textContent},
failOk: true,
load: function(data) {
Tooltip._masterTT.xhr = null;
Tooltip._masterTT.containerNode.innerHTML = data;
Tooltip._masterTT.domNode.width = "auto";
},
error: function(e) {
if (e.dojoType != "cancel") {
console.error(e);
}
}
});
Tooltip._masterTT.xhr = def;
});
on(dom.byId("groups"), ".group-link:mouseout", function(e) {
var target = e.target;
Tooltip.hide(target);
if (Tooltip._masterTT.xhr) {
Tooltip._masterTT.xhr.cancel();
}
});
});
As usual, I was over-thinking the problem, focusing on event registration rather than on simply creating the tooltips when the page loads. So, it's really stupidly simple:
query for the nodes
iterate through them and create the tooltips pointing to each node.
var myGroupsList = query("a.myGroupLink"); // query nodes based on class
array.forEach(myGroupsList,function(entry,i){ // iterate through
var grp_id = entry.id;
var content = '';
xhr.get({ // get data via xhr.get
url: "getGrpInfo.php",
handleAs: "json",
content: {
grp_id: grp_id,
content: "tooltip"
},
load: function(info) {
if(info == 0) {
content = '<div class="grpToolTip">';
content += ' Information about this group is confidential';
content += '</div>';
} else {
content = '<div class="grpToolTip">';
content += ' <img src="../ajax/getimg.php?id='+info.logo_id+'" />';
content += ' <div style="text-align:center">'+info.name+'</div>';
content += '</div>';
}
new Tooltip({ // create tooltip
connectId: [entry.id],
label: content
});
},
error: function() {}
});
});