I have an HTML page where there is a button to select a HTML file, and once the file is selected, some treatment is applied to it in JavaScript.
The code looks like this:
document.querySelector("#file").addEventListener("change", function() {
// Get filename from selected file
var filename = this.value.replace(/^.*[\\\/]/, '');
console.log(filename);
readTextFile("output/".concat(filename), function(text) {
// and then the actual solution is contained in this function readTextFile
});
});
I would like to be able to tweak this code to be able to apply the treatment to a batch of HTML files all at once. For instance, to all the HTML files in a given folder.
But I am new to JS and I honestly don't have a clue how I could do it.
Is there a way to have a multiple file selection buttons, so that I can apply the treatment to all the selected files?
Related
I am currently on a Chromebook using HTML, CSS, JS on repl.it, and I can't find a way to check the files in a folder.
I have a folder called objects containing a bunch of JSON files. I want the object dataQueue to hold every object, and I have got that working. But I don't want to have to specifically type out each file to make it run the function I made called getFile for every single file, as is done below in the code.
I am also trying to do this without any libraries (so I can understand everything), and also I want it to be able to run both as a site on the computer and on repl.it.
This is my current code:
//defined the dataQueue object where the object files
//will be stored
var dataQueue={};
//a function to get files by just inputting their
//filename and what i want to call them with in the future
function getFile(theFile,index){
//sets to a new request
var txtFile = new XMLHttpRequest();
//works with any file type, gets the specified file
txtFile.open("GET", theFile, true);
//I don't know what this does
txtFile.send(null);
//runs when the file is recieved
txtFile.onreadystatechange = function(){
//test to make sure it is ready
if(txtFile.readyState==4){
//add object file to dataQueue object
dataQueue[index]=JSON.parse(txtFile.response);
}
}
}
//get each file individually
getFile("objects/ship1.json","ship1");
getFile("objects/box1.json","box1");
getFile("objects/bigplatform1.json","platform1");
getFile("objects/bigbox1.json","bigbox1");
I want to be able to just add another JSON file to the objects folder and have it put in the dataQueue object without needing to add another getFile function.
I think a solution would be if I could somehow get a list of strings containing all of the filenames in the Objects folder, but I have tried finding a way to, and I couldn't find anything.
The question: How do I get each file name in a specific folder in a website's files?
I created a webserver using Python Flask. My "index.html" loads a table. I am planning to create a new field "view result" to each row of the table. On clicking view result, I should be able to visualize the data. I want the filename (corresponding to each entry of "view result"), to be the input file parameter to a javascript.
The filename should get passed here d3.csv("/static/<filename>.csv", function(data){...} which belongs to a file named view_data.js and data from corresponding file is visualized in another html page.
I have index.html page and view_data.js ready. How do I pass filename from index.html page to data.js for visualization?
For now I have hardcoded the filename in view_data.js.
Are you familiar with element selectors and events in javascript?
A simple implementation would be to set up event triggers that will fire when clicking each link, using the filename as that you store in a data attribute.
<a class="view-trigger" data-filename="filename_1.csv">view result</a>
<a class="view-trigger" data-filename="filename_2.csv">view result</a>
etc
You can set up the event using something like a specific class on each of the links (in the example view-trigger.
var resultLinks = document.getElementsByClassName(".view-trigger")
for(var i = 0; i < resultLinks.length; i++) {
(function(index) {
resultLinks[index].addEventListener("click", function(event) {
var filename = event.target.getAttribute('data-filename');
d3.csv("/static/" + filename + ".csv", function(data){...}
})
})(i);
}
I haven't tested this code so you may need to fix/adjust for your case. If you are not familiar with these concepts it's worth reading a bit more about them.
Also, d3.js also seems to come with utilities to do DOM selection and handling events, so you may want to use those instead.
Is it possible to get a fileEntry object in Chrome Apps by opening a file via Drag'n'Drop? When I drop a file into my app I only get a file object which seems to be unrelated to the file system. I can't use that object to save the file after changing it.
I get the file like this:
document.body.addEventListener('drop', function (event) {
file = event.dataTransfer.files[0]
});
What I want to do
I'm developing a text editor and I want to add a feature to open a file by dragging it into my app.
As I said: I already get the content of the file, but I can't write changes back to the file since I need a fileEntry object in order to do so.
Okay, I just found it while inspecting the event object. In the event object there's a function called webkitGetAsEntry() to get the fileEntry object. Here's the correct code:
document.body.addEventListener('drop', function (event) {
fileEntry = event.dataTransfer.items[0].webkitGetAsEntry();
});
This is the object you can use to write changes back to the file system.
Code for reference:
// Of course this needs the "fileSystem" permission.
// Dropped files from the file system aren't writable by default.
// So we need to make it writable first.
chrome.fileSystem.getWritableEntry(fileEntry, function (writableEntry) {
writableEntry.createWriter(function (writer) {
// Here use `writer.write(blob)` to write changes to the file system.
// Very important detail when you write files:
// https://developer.chrome.com/apps/app_codelab_filesystem
// look for the part that reads `if (!truncated)`
// This also is very hard to find and causes an annoying error
// when you don't know how to correctly truncate files
// while writing content to the files...
});
});
On click of a button called result, I want to read and display a text file (which is present in my local drive location say: C:\test.txt) using Javascript function and display the test.txt file contents in a HTML text area.
I am new to Javascript,can anyone suggest the code for Javascript function to read and display the contents of .txt file?
An Ajax request to a local file will fail for security reasons.
Imagine a website that accesses a file on your computer like you ask, but without letting you know, and sends the content to a hacker. You would not want that, and browser makers took care of that to protect your security!
To read the content of a file located on your hard drive, you would need to have a <input type="file"> and let the user select the file himself. You don't need to upload it. You can do it this way :
<input type="file" onchange="onFileSelected(event)">
<textarea id="result"></textarea>
function onFileSelected(event) {
var selectedFile = event.target.files[0];
var reader = new FileReader();
var result = document.getElementById("result");
reader.onload = function(event) {
result.innerHTML = event.target.result;
};
reader.readAsText(selectedFile);
}
JS Fiddle
Using $.ajax() function: http://api.jquery.com/jQuery.ajax/
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
As You've mentionned HTML, I assume you want to do this in a browser; Well the only way to access a local file in a browser is by using the File API, and the file can only be obtained via a user's manipulation such selecting a file in an <input type='file'> element, or drag&dropping a file in your page.
We could achieve this by, I should say, creating a virtual file!
Storing the contents of the text file into a Javascript string variable. However, one should consider all new lines and other special symbols\characters and etc.!
We than can markup a script tag in our HTML to load that *.js Javascript like this:
<script src="my_virtual_file.js"></script>
The only difference here is that a text file that could contain:
Goodnight moon
Follow the white rabbit
In a Javascript script string variable should look like this:
var my_virtual_file = "Goodnight moon\nFollow the white rabbit";
Later on, you can access this variable and treat it as you wish...
A programming language like Javascript that follows standards like ECMAScript, gives you a wide range of capabilities to treat and convert data from one type into another.
Once you have your Javascript script loaded, you can then access that variable by any button in your HTML by assigning a function call on its onclick attribute like this:
<button onclick="MyVirtualFile()"></button>
And ofcourse, you just add a script tag to your HTML, like this:
<script>
functiion MyVirtualFile(){
alert(my_virtual_file);
};
</script>
... or your may just create and import another Javascript script containing that same function, under your desire.
If you are concerned about how much information you can store into a Javascript string variable, just take a look at this interesting (and old as this one :D) SO thread.
Lets see if this snippet works :):
var my_virtual_file = "Goodnight moon\nFollow the white rabbit"
function MyVirtualFile(){
alert(my_virtual_file);
// Do anything else with your virtual file
};
<!DOCTYPE html>
<html>
<head>
<script src="my_virtual_file.js">
</script>
</head>
<body>
<h1>HTML Javascript virtual file</h1>
<button onclick="MyVirtualFile()">Alert my_virtual_file</button>
</body>
</html>
You can programatically access and dynamically change the contents of your Javascript script, but you should remind that you need to reload your HTML so the browser can load the new contents.
On your filesystem, you can just treat this *.js as a *.txt file, and just change its contents keeping in mind the Javacript.
I am working on an interface that allows the to access the file system on the client side. The user should be able to browse through the file system, select a directory and my system will display list of files and sub-directories of the selected directory.
I have tried using HTML5 File API, but that apparently only allows users to select files (not folders).
Any pointers/help in this direction will be appreciated.
This cannot be done in JavaScript as it would be a potential security issue. Only files selected by the user via a file dialog can be accessed using JavaScript.
Here's a pretty nice article on the File API if you haven't come across it yet.
If it's still an open issue, then let me give you a solution that might work for you.
HTML
File input for selecting a directory:
<input type="file" id="file-input" webkitdirectory="" directory=""/>
JavaScript
The following script collects all files from the given folder and from ALL sub folders.
Even from sub-subfolders, etc.
$("#file-input").on("change", function(e) {
var thefiles = e.target.files;
$.each(thefiles, function(i, item) {
var thefile = item;
var reader = new FileReader();
reader.onload = function() {
files.push(thefile);
};
reader.readAsArrayBuffer(thefile);
});
});