Currently I am making a program in which works as a text editor. I have a section where you can rename the title, and when you save, it takes that document.getElementById('title').innerHTML and makes it the .txt name.
For example:
If the title div had the innerHTML of "Document", the file would be called "Document.txt".
My problem is that I want it to also upload a file and take its file name.
For example:
I uploaded a file called "Document.txt", and the function makes the title "Document". (I am using a .replace('.txt','') to make it not show in the title and a += '.txt' to make the file actually a .txt when saved.
Anyone know how to make the file name of the uploaded document using an <input type='file'> a string to be used elsewhere?
Here is some code to put it in perspective:
var id = function(id){return document.getElementById(id)};
function readText(that)
{
var reader = new FileReader();
reader.onload = function(e)
{
var output = e.target.result,
name = FILENAMEFIND();
id('page').innerHTML = output;
id('title').innerHTML = name;
}
reader.readAsText(that.files[0]);
}
Ok, I figured it out myself:
var id = function(id){return document.getElementById(id)},
input = id("upfile"),
file = input.value.split("\\"),
fileName = file[file.length-1]; // Take purely the file name
id('title').innerHTML = fileName; // Outputted to title div
Related
I am now trying to set the dataUrl of JSZip to textarea using document.getElementById('fileContent').value = fileData; . But Once I did that, the site and browser became no response without any error. Does anyone have any idea what is wrong? Please really need help, and thanks for reading my question.
Every Thing goes well except after document.getElementById('fileContent').value = fileData;
Even I copy the DataURL and paste it into the textarea by myself, my site and browser stopped eventually.
I want to set the value inside a form element with action to send data by input value.
<textarea placeholder="Example Text" id="fileContent" name="fileContent" data-name="fileContent" class="w-input" spellcheck="false"></textarea>
<script>
function getfile() {
var zip = new JSZip();
for(let i = 0; i < file.length; i++){
var caltor = i+1;
var aFileName = "image"+caltor+".jpg";
var aContent = dataURItoBlob(file[i]);
zip.folder("Image_folder").file(aFileName, aContent)
}
zip.generateAsync({type:"base64"})
.then(function (content) {
fileData = "data:application/zip;base64,"+content;
document.getElementById('fileContent').value = fileData;
});
}
</script>
I have tried a lot of possibilities, but most of them don't work or require modules, but I don't know how to do this in vanilla javascript.. I really need some help.. Thanks. (Sorry for my bad English, I'm french)
My script : (don't really work, just read)
<script type="text/javascript">
var fso, ts, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.OpenTextFile("pub.txt", 1);
s = ts.ReadLine();
</script>
Reading a text file:
fetch('file.txt')
.then(response => response.text())
.then(text => console.log(text))
// outputs the content of the text file
Using Jquery:
$("#div7").load("ajax.txt");
Try this out!
<input type="file" onchange="readFile(this)" />
<script>
function readFile(input) {
let file = input.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function () {
document.getElementById("app").innerHTML = `<p>${reader.result}</p>`;
};
reader.onerror = function () {
console.log(reader.error);
};
}
</script>
document.querySelector("input[type='file']").addEventListener("change", function(){
if(this.files[0]){
this.files[0].text()
.then(val => {
document.querySelector("p").textContent = val;
})
}
})
<label>Pick One Text File</label><br/>
<input type="file" accept="text/plain" multiple="false"> <br/>
<label>File Will Show up here in the text box</label><br/><br/>
<p></p>
Edit: a working example here
https://codepen.io/engeslamadell/pen/WNrVPeG
did you tried this
<script type="text/javascript">
//this is the input with type file
document.getElementById('inputfile')
.addEventListener('change', function() {
var fr=new FileReader();
fr.onload=function(){
document.getElementById('output')
.textContent=fr.result;
}
fr.readAsText(this.files[0]);
})
</script>
you also have these FileReader methods
FileReader.readAsArrayBuffer(): Reads the contents of the specified input file. The result attribute contains an ArrayBuffer representing the file’s data.
FileReader.readAsBinaryString(): Reads the contents of the specified input file. The result attribute contains the raw binary data from the file as a string.
FileReader.readAsDataURL(): Reads the contents of the specified input file. The result attribute contains a URL representing the file’s data.
FileReader.readAsText(): Reads the contents of the specified input file. The result attribute contains the contents of the file as a text string. This method can take encoding version as the second argument(if required). The default encoding is UTF-8.
source: https://www.geeksforgeeks.org/how-to-read-a-local-text-file-using-javascript/
recently I have been trying to grab HTML form input data, add a prefix, then write that back into a <div> For example:
HTML:
<h1>Please enter Details</h1><hr>
GUID (Generator):<div id="guidInput" style="display:inline;">
<!-- Changed to an onkeyup="" method. Works the same but with less code. -->
<input onkeyup="gen()" id="guidText" style="height: 16px;"></input>
</div>
ID:<div id="idInput" style="display:inline;">
<!-- Changed to an onkeyup="" method. Works the same but with less code. -->
<input type="number" type="number" onkeyup="gen()" id="idText" style="height: 16px;"></input>
</div>
<div id="command" class="command"></div>
JS:
$(document).ready(function(){
var command = ""; /*Here for future developement*/
command += ""; /*Here for future developement*/
document.getElementById('command').innerHTML = command;
});
function gen() {
var id = $('#idText').val();
var guid = $('#guidText').val();
var command = ""; /*Here for future developement*/
var tags = [];
tags.push("GUID "+guid);
tags.push("ID "+id);
command += tags.join("<br>");
command += ""; /*Here for future developement*/
document.getElementById('command').innerHTML = command;
}
This does what I want it to: https://imgur.com/a/QrwD7 But I want the user to download the output as a file. To do this I implemented FileSaver.js, and added this code to my files:
HTML (placed above the <div id="command" class="command"></div>):
<button onclick="saver()">Save</button>
JS:
function saver() {
var text = document.getElementById("command").innerHTML;
var newText = text.replace(/(<([^>]+)>)/ig,"");
var filename = ("File")
var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
saveAs(blob, filename+".txt");
}
That grabs the content of the <div> containing the output, and triggers a download of File.txt. The contents of this file look like this (from imgur.com link above.):
GUID qwertyuiop<br>ID 12345
This is where I'm having my problem. I NEED the file to look like this:
GUID qwertyuiop
ID 12345
With a line break after every part. the <br> is for displaying it on the site, but I need some way to make sure it's on a separate line in the downloaded file, and having no HTML tags in the file.
var newText = text.replace(`<br>`, `\n`).replace(/(<([^>]+)>)/ig,"");
or
function gen(delimiter) {
// ... //
command += tags.join(delimiter);
return command;
}
function saver() {
// ... //
var newText = gen(`\n`);
// ... //
}
Your code is violating SRP: Single Responsibility Principle.
You are trying to do two things at the same time.
Prefixing and formatting in HTML are two different concerns and they should be separated.
After that, the answer will become obvious.
I'm trying to figure out the flow of using google's scripts to copy images from a user's hard drive to a public folder on their Google Drive. (see https://developers.google.com/apps-script/reference/utilities/utilities#unzip%28BlobSource%29 ) Question is, do I have to write a google script that I publish as a web app from script.google.com, or can I have the script inside the javascript on the client's browser? Google has a sample of uploading images one at a time: "developers.google.com/drive/web/quickstart/quickstart-js"
I would like to upload one zipped file of images, unzip them and then reduce the size before they are stored in the user's Google Drive.
Here is some code that unzips files, but it looks like they are running this from script.google.com; it does not work: (http://webcache.googleusercontent.com/search?q=cache:NsTvlj17H4MJ:ctrlq.org/code/19506-google-drive-hosting&client=firefox-a&hs=ZEF&hl=en&gl=us&strip=1)
This is a script that I modified for another user that allows for multiple files (validation could probably limit file types to images) to be uploaded from the user's hard drive to a specific folder. The folder would be set to share publicly. You would simply change the folderID string to the string that matches the folder where you wanted to files to arrive. Put this script in a Google Sites page, and change the id in the doPost(e) function, and it should do what you want it to do. I'm not sure about the zipping and unzipping. You would publish the script in a google site as a public webapp widget.
You can see the UiApp interface here, but if you try to upload something, you will get an error because I've removed the folderId link to my drive since I put this answer live. If you need more explanation about how or why it works, let me know. Use the + and - buttons to add more files to the upload, or remove a file that you don't want to include. The files can be zips or any file type, but there isn't code included to unzip anything after it's uploaded.
//modified from script found here http://www.googleappsscript.org/miscellaneous/creating-form-elements-dynamically-using-google-apps-script-gas
//additional help from Serge to fix an error in my original code.
function doGet() {
var app = UiApp.createApplication();
var panel = app.createVerticalPanel();
var formPanel = app.createFormPanel();
var instructionsLabel = app.createLabel('Put your instructions here');
var filesLabel = app.createLabel('Add Files to Upload');
var table = app.createFlexTable().setId('table').setTag('0'); //Here tag will count the number of files
//Write the header for the table
var header = app.createLabel('File(s)');
table.setWidget(0, 0, header);
//Add the first row of files
addFirstRow(app);
var hidden = app.createHidden().setId('hiddenRowHolder').setName('hidden').setValue(table.getTag());
//Add a button to submit the info
var button = app.createSubmitButton('Upload File(s)');
panel.add(instructionsLabel).add(filesLabel).add(table).add(hidden).add(button);
formPanel.add(panel);
app.add(formPanel);
return app;
}
function addFirstRow(app){
var table = app.getElementById('table');
var tag = parseInt(table.getTag());
Logger.log(tag);
var numRows = tag+1;
if(numRows >1){
table.removeCell(numRows-1, 5);
table.removeCell(numRows-1, 4);
}
Logger.log(numRows);
var uploadWidget = app.createFileUpload();
table.setWidget(numRows, 0, uploadWidget);
table.setTag(numRows.toString());
addButtons(app);
}
function addButtons(app){
var table = app.getElementById('table');
var numRows = parseInt(table.getTag());
//Create handler to add/remove row
var addRemoveRowHandler = app.createServerHandler('addRemoveRow');
addRemoveRowHandler.addCallbackElement(table);
//Add row button and handler
var addRowBtn = app.createButton('+').setId('addOne').setTitle('Add row');
table.setWidget(numRows, 4, addRowBtn);
addRowBtn.addMouseUpHandler(addRemoveRowHandler);
//remove row button and handler
var removeRowBtn = app.createButton('-').setId('removeOne').setTitle('Remove row');
table.setWidget(numRows, 5, removeRowBtn);
removeRowBtn.addMouseUpHandler(addRemoveRowHandler);
}
function addRemoveRow(e){
Logger.log(e.parameter.source);
var app = UiApp.getActiveApplication();
var table = app.getElementById('table');
var tag = parseInt(e.parameter.table_tag);
var hidden = app.getElementById('hiddenRowHolder');
var source = e.parameter.source;
//Logger.log(tag);
if(source == 'addOne'){
table.setTag(tag.toString());
hidden.setValue(tag+1);
addFirstRow(app);
}
else if(source == 'removeOne'){
if(tag > 1){
//Dcrement the tag by one
var numRows = tag-1;
table.removeRow(tag);
//Set the new tag of the table
table.setTag(numRows);
hidden.setValue(numRows);
//Add buttons in previous row
addButtons(app);
}
}
return app;
}
function doPost(e) {
var numFiles = Number(e.parameter.hidden);
Logger.log(numFiles);
for (var i = 1; i<=numFiles; i++){
var fileBlob = e.parameter['file'+i];
var newFile = DocsList.getFolderById("YOUR FILE FOLDER ID").createFile(fileBlob);//replace string with folder id where you want to place your files
}
var app = UiApp.getActiveApplication();
var label = app.createLabel(numFiles +' file(s) uploaded successfully');
app.add(label);
return app;
}
I'm trying to read an input type="file" tag into a javascript string. I know this should be simple but I simply cannot get my code to work. The file is plain .html. Here's what I have
<h3>Select location of html file.</h3>
<form onSubmit="submitButtonPressed()">
<input type="file" id="classList" />
<input type="submit" />
</form>
<script>
var reader = new FileReader();
var htmlFile = document.getElementById("classList").files[0]; //read the file selected with the <input> tag
reader.readAsText(htmlFile);
var htmlText = reader.result; //and create a string with the contents
function submitButtonPressed() {
var lengthOfText = htmlText.length;
alert("It is " + lengthOfText + " characters long");
}
</script>
I'm just trying to create a string that contains the contents of the .html file selected by the input tag. I can't figure out why htmlText doesn't contain the contents of the .html file, could someone explain what I'm doing wrong?
this is the right answer for you :
HTML5 File API: How to see the result of readAsText()
reader.onload = function(e) {
// e.target.result should contain the text
};
reader.readAsText(file);
so i guess you will have to check on pressing the button if the file was loaded or not , maybe it is still in progress , or encountered an error