Access file from JS running localy - javascript

I need to load a simple .CSV file from JS (That's not the problem here), but the "script" need to be portable (i will use it as the screen on a competition), and score data will be inserted in the CSV, and JS will be updating it's data based on the CSV.
But my problem here is: I need to run it without apache or a server, because i cant make shure the people who will use it, will have apache and also Internet... It need to be opened from a folder (Just a HTML with JS, and a file in the same folder with the .CSV)
When i try to access files from jQuery ($.get(..., ..., "jsonp"), and $.get()), Chrome output this error:
XMLHttpRequest cannot load file:PATHTOTHEFILE Origin null is not allowed by Access-Control-Allow-Origin.
This happens because the browser blocks it's content (for security reasons).
How can i "deal" with this problem, or do you know a better solution, to save some simple data and read it from JS without secury problems?
Thanks

you need to add --allow-file-access-from-files to the chrome startup command line
make a BAT file and get you users to click that to start your app
%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe ^
--allow-file-access-from-files ^
http://bing.co.uk
swap out the http:// for you file url.

You can use html5 FileReader. But in this way you have to select file.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<label for="files">Path to file: </label><input type="file" id="files" name="files[]"/>
<script>
function handleFileSelect(evt) {
var files = evt.target.files;
var f;
for (var i = 0; f = files[i]; i++) {
if (!f.type.match('text.*')) {
continue;
}
var reader = new FileReader('test.html');
reader.onloadend = (function () {
return function(e) {
alert(e.target.result);
};
})();
reader.readAsText(f);
}
}
var fileSerf= document.getElementById('files');
if (fileSerf){
fileSerf.addEventListener('change', handleFileSelect, false);
}
</script>
</body>
</html>
example: http://jsbin.com/ozeyag/293/

Related

Using three.js: .glb 3d model shows up locally but not on github server, receive SyntaxError: Json.parse

I tried to use three.js to display a 3d model in my personal webpage. The model can be successfully displayed on my local server, however it failed to show up on my web server and I got an error like this:
(links to my .glb file, the main.js, and the index.html file)
I opened my browser web tools and the HTTP response data of my .glb model looks like this:
Any ideas would be highly appreciated.
BH
currently the main.js file looks like this:
$(document).ready(function(){
$nav = $('.nav');
$toggleCollapse = $('.toggle-collapse');
/** click event on toggle menu */
$toggleCollapse.click(function(){
$nav.toggleClass('collapse');
})
});
so it's hard to say exactly what the problem is now, but I'm guessing it was different before.
Without knowing the details of the server code [since you said it was fine in your local server but not on your main server] it's difficult to know the exact details of the issue, but one alternative for loading models without any server at all [but also works through servers] is by making another program [HTML file] that creates a JavaScript loadable file containing the data URL of the file loaded, which can then be included into the main HTML file with a standard script tag [or programmatically], then with the THREE.JS model loader, simply use the dataURL instead of the model URL.
I've persoanlly used this method many times without any server, not even a local server, and I've been able to load all kinds of models [and other files in general].
An example HTML file / code would look something like this:
BH
<br>
data URL-ifier
<br>
<input id="filePicker" type="file">
<br>
<div id="kinTayner"></div>
<script>
filePicker.onchange = () => {
var fr = new FileReader()
fr.onload = () => {
a = document.createElement("a")
kinTayner.innerHTML=""
a.download = filePicker.files[0].name+".html"//or .js,
//but .html files can actually be included in a
//project the same as JS scripts, which can be
//useful if you want to view it quickly in the
//browser
a.innerHTML = "Downlaod the DATA-Urlifier file?!"+
"<br>On GitHub might have to right click->save link as"
var id=Date.now()
a.href = URL.createObjectURL(new Blob([
`
/*BH
\n
<br>
Duel HTML and JavaScript File,
\n<br> can be opened in browser and
\n<br> included as a script, since JavaScript
\n<br>doesn't recognize HTML tags in comments,
\n<br> and JS comments don't affect HTML
<script>
if(!window.dataURLified) {
window.dataURLified = function(d) {
window._fileData_${id} = d;
//to access from console for later use
var m = document.getElementById("${id}")
if(!m) return;
m.innerHTML = "<h1>Your file data!</h1>"+
"<br><h2>"+d.name+"</h2><br>"+
"<a href='" + d.url +
"' target='_blank'>View your file [or right click to download]</a>"
}
}
</`+`script>
<div id="${id}"></div>
<style>
</style>
*/
//<script>
dataURLified({name:"` +
filePicker.files[0].name + `", url: "`+
fr.result
+`"})
// </`+`script>
`
], {type:"text/html"}))
kinTayner.appendChild(a)
}
fr.readAsDataURL(filePicker.files[0])
}
</script>
Then in your main code you can read it by including a script with that name [even if the extension is .html] and define a global function dataURLified [or whatever] to handle the data, here's an example file code [to be used after the above file is generated, and placed in the same directory as the following code, or hosted online, and in the input box enter the URL of that file and open the console]:
<h2>BH</h2><br>
<h3>HTML Fileized Loader</h3>
<input id="loader"> -- enter the name of the file you want to load as script [that was generated b4]
<script>
var files = []
function loadSc(name) {
return new Promise((r,j) => {
var sc = document.createElement("script")
sc.onload=()=>{
r({msg:"Loaded",fl:files[files.length-1]})
}
sc.onerror=(e)=>{
j({msg:"Nope",details:e})
}
sc.src=name;
document.body.appendChild(sc)
})
}
function dataURLified(d) {
//use it here
files.push(d)
}
///somewhere in code, can just call loadSc, just an example
loader.onchange = () => {
loadSc(loader.value)
.then(r=> {
console.log(myFile=r.fl,r.msg,"Use myFile.url for the path!")
}).catch(e=>{
console.log("PRoblem!",e)
})
}
</script>

How to read local text file in JavaScript automatically [duplicate]

This question already has answers here:
How to read a local text file in the browser?
(23 answers)
Closed 6 years ago.
I want to read a local text file from my local html file, so I tried to follow the solution in this thread Javascript - read local text file but the suggested solution does not work for me either:
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
When I call the function readTextFile("file:///D:/test/text.txt"); no error does show up in firebug but no alert is shown neither. I use Windows und Firefox 51.0.1 (64-Bit).
I don't want to use the function FileReader() in combination with a button <input type='file' onchange='openFile(event)' ... since the text file needs to be read automatically when loading the page. So how can I make work the solution above?
Reading the thread linked it looks like others also have problems with that solution although the thread is marked as solved.
Complete HTML and JavaScript file as an example for reading client side data files. Client side files can only be accessed by the FileReader, specifying a user selected file.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadFile(o)
{
var fr = new FileReader();
fr.onload = function(e)
{
showDataFile(e, o);
};
fr.readAsText(o.files[0]);
}
function showDataFile(e, o)
{
document.getElementById("data").innerText = e.target.result;
}
</script>
</script>
</head>
<body>
Select file to read <input type="file" onchange="loadFile(this)">
<pre id="data"></pre>
</body>
</html>
As a general rule, it's not possible to access the local file system from JavaScript, so your code example shouldn't and couldn't work because of browser security.
However, there's the File and FileReader API which would allow you to read the contents of a file from an <input type="file" /> and is, in reality, your only option for this sort of thing - You could use FileReader.readAsText() to access the files contents. This is a good resource for further information:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
The easiest way to solve my problem is to change the text file to a .js file, save it in the same folder and include it in the html file by <script src="test.js"></script>

How to define a local file as a DOM object?

I want to parse data in my computer using JavaScript. I use papa parse .
In PapaParse documentation it has been stated local files can be parsed by following code ;
Papa.parse(file, config)
In documentation they say file is a File object obtained from the DOM. How can I define a local file as an DOM object ?
I doubt that this is possible as it would be a huge security problem. Imagine someone could just read files from your computer when you load their javascript through your browser. You'll have to go with a file picker.
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<input type="file" id="csv-files" multiple>
<script>
var handleFileSelect(evt) {
var file = evt.target.files[0];
// do stuff with that file e.g. Papa.parse(file)
}
$(document).ready(function() {
$("#csv-files").change(handleFileSelect);
});
</script>
the above code uses jQuery to load the files when the file picker was used.
see joyofdata.de/parsing-local-csv-file for reference. Concise explanation.

Convert extension and open it using an application

I got a a script wherein I want to convert the extension to another one then open it using a specific application.
For instance, I got .mht file located in my Desktop. An html file with internal javascript on it.
What I want to happen is when I open the HTML file on internet explorer and click on the hyperlink, it should convert .mht file into .docx and open it using Microsoft Word. Unfortunately, my below code does not work, if i click the hyperlink, it does opens up Microsoft Word but giving me an error message saying that the file cannot be found. Can someone assist me with this please? Thanks in advance, will much appreciated.
<HTML>
<HEAD>
<script type="text/javascript">
<!--
function openDocument(file)
{
try
{
var Word = new ActiveXObject("Word.Application")
var file;
file = file.split(".");
file = file[0]+".docx";
Word.Visible = true
Word.Documents.Open(file)
}
catch(exception)
{
if(Word)
{
alert(exception.message)
Word.Quit()
}
window.location.href = file
}
}
// -->
</script>
<TITLE>Launch Word - Local</Title>
</HEAD>
<BODY>
Summary
</BODY>
</HTML>
For security purpose, Javascript can't write on the filesystem, so it is impossible to change the extension of a file.
You should be able to do something with the new FileSystem API (check that tutorial : http://www.html5rocks.com/en/tutorials/file/filesystem/), but it is available only on Chrome (http://caniuse.com/#feat=filesystem)
EDIT:
With an ActiveX, using GetFile may work:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.GetFile("c:\\myfile.mht");
file.name = "newName.newExt";

Javascript dynamically show local file

I have a local text file which is kept changing by other programs. I want to write a html and javascript based web page to show the content of file dynamically. I have searched in google and found that most solutions require to get this text file via html element. I wonder if there is a way to get the file via a fixed path(lets say it is a string of the file directory) in javascript. I am using Javascript fileReader. Any help will be appreciated.
This is not possible using javascript running inside the browser. You will not be able to do anything outside the browser.
EDIT:
You could run a Node.js server though that runs on localhost and does your file operations you desire. You could build a API so your html page that you load in the browser calls your serverscript to do your file operations.
Do you understand what I mean?
How much information does the text file hold, Depending on your scenario it might be worth looking into javascript localstorage W3SCHOOLS local storage. Would that help your situation ?
What you can do is allow the user to choose the file of interest, using a file-input. Once done, the browser wil have access to the file, even though the JS wont have access to the file's full-path.
Once the user has chosen the file, you can reload it and refresh the view pretty-much as often as you please.
Here's a short demo, using a file input (<input type='file'/>) and an iframe. You can pick pretty much anything the browser will normally display, though there are limits on the size of the file that will work - due to the limit of the length of a URL - the file's data is turned into a data-url and that url is set as the source of the iframe.
As a demo, pick a file and then load it. Now, open the file in another program and change it. Finally, press the load button once again - the new content now fills the iframe. You can trigger the loading of the file by a timer or any other event in the page. As far as I'm aware, you cannot re-load it when it changes, since there's no notification from the OS - you have to use a button, timer, element event or whatever. Basically, you have to poll for changes.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
// uncomment this line for on-demand loading.
byId('loadBtn').addEventListener('click', onLoadBtnClick, false);
}
// fileVar is an object as returned by <input type='file'>
// tgtElem is an <iframe> or <img> element - can be on/off screen (doesn't need to be added to the DOM)
function loadFromFile(fileVar, tgtElem)
{
var fileReader = new FileReader();
fileReader.onload = onFileLoaded;
fileReader.readAsBinaryString(fileVar);
function onFileLoaded(fileLoadedEvent)
{
var result,data;
data = fileLoadedEvent.target.result;
result = "data:";
result += fileVar.type;
result += ";base64,";
result += btoa(data);
tgtElem.src = result;
}
}
function onLoadBtnClick(evt)
{
var fileInput = byId('mFileInput');
if (fileInput.files.length != 0)
{
var tgtElem = byId('tgt');
var curFile = fileInput.files[0];
loadFromFile(curFile, tgtElem);
}
}
</script>
<style>
</style>
</head>
<body>
<button id='loadBtn'>Load</button><input id='mFileInput' type='file'/><br>
<iframe id='tgt'></iframe>
</body>
</html>
you can use nodejs to watch for a filechange using watchfile module, if you just want to watch the filechange and its content. you can run following code using node, but it only consoles the file changed in your terminal.
var fs=require('fs');
fs.watchFile('message.text', function (curr, prev) { //listens to file change
fs.readFile('message.text', function(err,data){ //reads the file
console.log(data.toString()); //consoles the file content
});
});

Categories