I am working on a project which must be self contained and able to run without an internet connection. It's is for video presentations and I need to import a .txt file which includes chapters and loop information such as Chapter Title, Looping point and chapter end point (both in frames). However, there is no client-side include script to include a text file.
What would be the best way for me to store or access a local text file so that I can iterate over it and build my chapters object? HTML5 local storage? Hacking by including a hidden iframe that loads the text file then grab that body content via JavaScript? Any help on this issue would be greatly appreciated.
Thanks!
For your question "Need Access to Local Text File via JavaScript" is very similar to this question here: Local file access with javascript
The Answer is there really isn't a good way to access a local file if you are using javascript in a browser. If its just a text file on the same machine without a http/webserver you may run into some problems, as in javascript the ability to read a local file is disabled by default in most browsers. In chrome you can disable this security-feature by adding the following flag when starting the browser from command-line.
--disable-web-security
If your data is structured json, xml, csv, you can bring it in using an AJAX call if the file is hosted on a server accessible with HTTP. Without using an http ajax call, another possible solution as mentioned in the question link above:
Just an update of the HTML5 features http://www.html5rocks.com/en/tutorials/file/dndfiles/
This excellent article will explain en detail the local file access in
Javascript. Summary from the mentioned article:
The spec provides several interfaces for accessing files from a
'local' filesystem:
File - an individual file; provides readonly information such as name,
file size, mimetype, and a reference to the file handle. FileList - an
array-like sequence of File objects. (Think or dragging a directory of files from the desktop). Blob -
Allows for slicing a file into byte ranges.
-- #Horst Walter
As shown below you can have a "file upload" input selection, and simply have your file path as a default option for the input"
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
You can use AJAX to read the text file.
with javascript you can't edited, you can only read it.
an example will be :
1- create a text file "page.txt"
2- create a html page with this code
<!DOCTYPE html>
<html>
<body>
<script>
text = new XMLHttpRequest();
text.open("GET","page.txt",false);
text.onload = function(){
document.write(text.responseText);
}
text.send();
</script>
</body>
</html>
Related
I want read a local txt file with javascript on chrome browser. So, I use <input type="file" .../> and when I select any txt file, I read it. But I dont want select file. I need to load the file with the file path. How is this possible?
Thanks
You can't do this. This is obviously because of security implications: imagine if any website you visit could read your FileZilla preferences file, which contains all your unencrypted FTP passwords? I bet you wouldn't like that.
You have to obtain a File reference (e.g. from an event handler) before being able to manipulate it. More info.
if you want to read file data opened from file dialog:
function readFile(){
var t = document.getElementById("file")
var o = new FileReader();
o.onload = function(t) {
console.log(t.target.result);
}
o.readAsText(t.files[0]);
}
edit: you can't just open files without selecting it first
An ipython notebook is a document that is read by the browser that contains both rich text and python code.
In scientific computing ipython notebooks are often used to perform an analysis some input data file that resides on the local file system.
Instead of manually pasting the full path of the file containing the data into a variable, would be convenient to be able to launch an open-file dialog in order to browse the local file system and select the file. The full path of the file should be returned in a variable (in python).
This can be achieved launching an open-file dialog from a GUI toolkit (i.e. QT). For an example see IPython Notebook: Open/select file with GUI (Qt Dialog).
However, using QT has some disadvantages. First it is an additional dependency. Second it requires enabling the QT gui integration in the notebook and this results in conflicts with the inline plots (see here).
The question here is, is it possible to obtain the full path using only Javascript?
EDIT: The answer posted below only returns the file name, not the full-path.
Using the HTML5 construct <input type="file"> is possible to instruct the browser to open a file selector dialog. Then we need to bind a javascript function to the "changed event".
The javascript can use kernel.execute(command) to execute a command on the python kernel that assign a variable with the selected file path.
Here an example:
input_form = """
<div style="border:solid navy; padding:20px;">
<input type="file" id="file_selector" name="files[]"/>
<output id="list"></output>
</div>
"""
javascript = """
<script type="text/Javascript">
function handleFileSelect(evt) {
var kernel = IPython.notebook.kernel;
var files = evt.target.files; // FileList object
console.log('Executing orig')
console.log(files)
// files is a FileList of File objects. List some properties.
var output = [];
var f = files[0]
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</_Mli>');
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
var command = 'fname = "' + f.name + '"'
console.log(command)
kernel.execute(command);
}
document.getElementById('file_selector').addEventListener('change', handleFileSelect, false);
</script>
"""
def file_selector():
from IPython.display import HTML, display
display(HTML(input_form + javascript))
After the previous definitions putting in a cell file_selector() will display a button "Choose file" and after a file is selected the variable fname in the notebook will contain the file path.
References
http://www.html5rocks.com/en/tutorials/file/dndfiles/
https://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/
this other StackOverflow
"How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?"
has already cleared the question : you can't get local fullpath from HTML (5 or previous) interface due to security politic.
So it is normal that you need QT (or equivalent) to get what you need.
I've been searching a Flash equivalent, but it seems that you may only have it with AIR according to this StackOverflow :
"Flex - How to browse and get the full path of a file on local machine's file system?"
Is there a possible way to read a local file in JavaScript.
MyFolder:
db.csv
Parse.js
Trying to fetch the contents of file db.csv in Parse.js, But in vain.
Can you share some links where I can get enough knowledge how to read a file.
Running Instruments in Xcode5, with test scripts in .js file where I have to feed in some values from a .csv file.
iOS UIAutomation, apple provides an api for running a task on the target's host.
performTaskWithPathArgumentsTimeout
Using this, we can have a bash script to printout the contents of a file that we wanted to fetch in the first case.
Bash script can be as simple as this for this requirement.
#! /bin/bash
FILE_NAME="$1"
cat $FILE_NAME
Save it as for example FileReader.sh file.
And in your automation script,
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout(executablePath,[filePath,fileName], 15);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
where in,
executablePath is where the command need to be executed.
var executablePath = "/bin/sh";
filePath is the location of the created FileReader.sh file. When executed, outputs the content to standard output (in our requirement).
[give full absolute path of the file]
fileName is the actual file to fetch contents from.
[give full absolute path of the file] In my case I had a Contents.csv file, which I had to read.
and the last parameter is the timeout in seconds.
Hope this helps others, trying to fetch contents (reading files) for performing iOS UIAutomation.
References:
https://stackoverflow.com/a/19016573/344798
https://developer.apple.com/library/iOS/documentation/UIAutomation/Reference/UIAHostClassReference/UIAHost/UIAHost.html
If the file is on the same domain as the site you're in, you'd load it with Ajax. If you're using Ajax, it's be something like
$.get('db.csv', function(csvContent){
//process here
});
Just note that the path to the csv file will be relative to the web page you're in, not the JavaScript file.
If you're not using jQuery, you'd have to manually work with an XmlHttpRequest object to do your Ajax call.
And though your question doesn't (seem to) deal with it, if the file is located on a different domain, then you'd have to use either jsonP or CORS.
And, just in case this is your goal, no, you can't, in client side JavaScript open up some sort of Stream and read in a file. That would be a monstrous security vulnerability.
This is a fairly simple function in Illuminator's host functions library:
function readFromFile(path) {
var result = target.host().performTaskWithPathArgumentsTimeout("/bin/cat", [path], 10);
// be verbose if something didn't go well
if (0 != result.exitCode) {
throw new Error("readFromFile failed: " + result.stderr);
}
return result.stdout;
}
If you are using Illuminator, this is host().readFromFile(path).
Is it possible to read manifest file contents from Javascript. Requirement is to upload a jar file, read the manifest file content and then display different fields based on manifest file in browser (client side) and then send data to server.
Here is a basic example, tested in chrome.
I've never seen a JAR manifest, but the simplistic code below worked on the demo JAR files i found floating around.
That part is not tricky anyway, ripping open the zip and grabbing the file is, and here's one way:
<html>
<form><input type=file></form>
<script src="http://stuk.github.io/jszip/jszip.js"></script>
<script src="http://stuk.github.io/jszip/jszip-load.js"></script>
<script src="http://stuk.github.io/jszip/jszip-inflate.js"></script>
<script>
function getManifest(e){
var file=e.target.files[0];
var reader = new FileReader();
reader.onload = function(e) {
var zip = new JSZip(e.target.result);
var manifest = zip.files['META-INF/MANIFEST.MF']
.data
.trim()
.split(/\s*\n+\s*/)
.map(function(a,r){
r=a.split(/\s*:\s*/);
this[r[0]] = r[1];
return this;
},{})[0];
alert(JSON.stringify(manifest, null, "\t"));
};
reader.readAsArrayBuffer(file);
}
document.forms[0].elements[0].onchange=getManifest;
</script>
</html>
of course, you'll want to swap out the file input for a binary ajax call, but it's about impossible to demo such interaction in a paragraph of code like a file input allows...
it's pretty easy, thanks to jszip. about that: see http://stuk.github.io/jszip/ for general info and http://stuk.github.io/jszip/examples/get-binary-files-xhr2.html for a binary ajax demo.
Supposing you talk about Java server app:
No it's not possible.
You need to expose the info from manifest somehow, e.g. through a REST API. See [RestEasy|http://www.jboss.org/resteasy].
And then read it through XmlHttpRequest.
PS: It's not a good idea to expose whatever in META-INF or WEB-INF - it's a security risk.
My company has a very strict intranet for work related, the net has a single doorway to allow files in and out. The doorway's security does not allow special kinds of files (*.txt, *.doc etc only), and even in those specific kinds of files, it searches for patterns that approve that the file is really that kind. (You can't simply disguise a *.zip file as a *.doc file.)
As a security project, I was told to find a way to bypass this system, and insert a single C language .exe file that says 'Hello World'.
What I thought was to change the extension to .txt, and base64 encode it so that it would be more acceptable for the system. The problem is, how to decode it once it's in. It's very easy on the outside, PHP or any other decent language can do it for me. However, in there, the only real language I have access to is JavaScript (on IE6 and maybe, MAYBE, on IE8).
So the question is as follows, can I use JavaScript to read a file from the file system, decode it, and write it back? or at least display the result for me?
Note that I don't ask for decoding/encoding a message, this one is easy, I look to decode encode a file.
JSON might be the answer you are looking for. It can actually do the trick.
Encode your txt file in JSON format. It is very likely for it to pass your company's doorway security
var myJsonData = { "text" : "SGVsbG8sIHdvcmxkIQ==" }; // <-- base64 for "Hello, world!"
Import your txt file using plain html script syntax
<script src="hello.txt" type="text/javascript"> </script>
That's it! Now you can access a JSON object using the Syntax:
alert(myJsonData.text);
To complete your job, get this simple Javascript base64 decoder.
You're done. Here's the (very simple) code I've used:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
<script src="base64utils.js" type="text/javascript"> </script>
<script src="hello.txt" type="text/javascript"> </script>
<script type="text/javascript">
function helloFunction() {
document.getElementById("hello").innerHTML = decode64(myJsonData.text);
}
</script>
</head>
<body onload="helloFunction();">
<p id="hello"></p>
</body>
</html>
Using only javascript (i.e. no plugins like AIR etc), browsers don't allow access to the file system. Not only is it not possible to write a file to the disk, it's not possible to even read it - browsers are very strict on that sort of thing, thank goodness.
You cannot do this with straight JS in the browser, security context and the DOM do not allow filesystem access.
You cannot do this with current versions of flash, older versions (pre 7 IIRC) had some security flaws that allowed filesystem access.
You could do this with a custom plugin, and possibly a signed Java applet, or COM (ActiveX component, IE only).
I would suggest working with IT regarding your intranet to open up the context/permissions needed in this case as that may be the shortest path to what you are wanting here. Alternative, you could create a command-line utility to easily encrypt/decrypt given files signed by a common key.
It all depends on how you can get the file in. If you have the base-64 encoded exe as a .txt, you could easily use Flash!
I'm not quite sure how you would implement this, but you can load a file into flash and as3 using flex.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import flash.net.FileReference;
import flash.net.FileFilter;
import flash.events.IOErrorEvent;
import flash.events.Event;
import flash.utils.ByteArray;
//FileReference Class well will use to load data
private var fr:FileReference;
//File types which we want the user to open
private static const FILE_TYPES:Array = [new FileFilter("Text File", "*.txt;*.text")];
//called when the user clicks the load file button
private function onLoadFileClick():void
{
//create the FileReference instance
fr = new FileReference();
//listen for when they select a file
fr.addEventListener(Event.SELECT, onFileSelect);
//listen for when then cancel out of the browse dialog
fr.addEventListener(Event.CANCEL,onCancel);
//open a native browse dialog that filters for text files
fr.browse(FILE_TYPES);
}
/************ Browse Event Handlers **************/
//called when the user selects a file from the browse dialog
private function onFileSelect(e:Event):void
{
//listen for when the file has loaded
fr.addEventListener(Event.COMPLETE, onLoadComplete);
//listen for any errors reading the file
fr.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
//load the content of the file
fr.load();
}
//called when the user cancels out of the browser dialog
private function onCancel(e:Event):void
{
trace("File Browse Canceled");
fr = null;
}
/************ Select Event Handlers **************/
//called when the file has completed loading
private function onLoadComplete(e:Event):void
{
//get the data from the file as a ByteArray
var data:ByteArray = fr.data;
//read the bytes of the file as a string and put it in the
//textarea
outputField.text = data.readUTFBytes(data.bytesAvailable);
//clean up the FileReference instance
fr = null;
}
//called if an error occurs while loading the file contents
private function onLoadError(e:IOErrorEvent):void
{
trace("Error loading file : " + e.text);
}
]]>
</mx:Script>
<mx:Button label="Load Text File" right="10" bottom="10" click="onLoadFileClick()"/>
<mx:TextArea right="10" left="10" top="10" bottom="40" id="outputField"/>
</mx:Application>
To decode it, look into http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/Base64Decoder.html
If the security system scans for patterns in files, it is very unlikely that it will overlook a base64-encoded file or base64-encoded contents in files. E-mail attachments are base64-encoded, and if the system is any good it will scan for potentially harmful e-mail attachments even if they are named .txt. The base64-encoded start of an EXE file is almost certainly recognized by it. So ISTM you are asking the wrong question.