How to read a local text file using javascript - javascript

I have a button in in view page. On clicking the button an function gets called.In that function am calling another function with location of file as parameter.In the second function i need to read the file specified in the location passed and show the contents in console.What i already tries is below
ReadFile : function(){
this.ReadTextFile("C:\Users\RFRANCIS\Downloads\Inv00008W.txt");
},
ReadTextFile: function(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);
}
But I am getting Access denied error.Please find me to solve this issue or suggest another method.I am testing this in IE11.

In order to access you local drive you need a valid URL for the file which probably looks more like file:///c:/ than what you have but you have a few overlapping issues here:
The url for a local file must start with file:///
You need to understand about escape characters and slashes in Javascript string literals (you need special syntax to express slashes in javascript)
When you fix these you are still going to get CORS security exceptions because (at least chrome) doesn't perceive local files as one domain. (To resolve this you either need to set you chrome up specially or use a proper localhost http-server on your local machine.

Related

How to read text file from filesystem in JavaScript

I have tried different approaches to read a text file from the local file system in JavaScript and display the content of the file in alert() but all to no avail.
Approach 1
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.response;
document.getElementById("content").innerText = allText;
alert(allText);
}
} else {
alert("Can't read the file");
}
}
rawFile.send(null);
}
readTextFile("FormulaQuestion.txt");
The FormulaQuestion.txt file is in the same directory with the html file, this approach shows an empty alert window on the browser
Approach 2 using fetch method
fetch('FormulaQuestion.txt')
.then(response => response.text())
.then((data) => {
alert(data);
})
This doesn't show anything
Approach 3 using JQuery
$.get('FormulaQuestion.txt', function (data) {
alert(data)
}, 'text');
This doesn't work either.
I am building a desktop application that uses a web browser control to load html file which is embedded into the application. The application reads the string from sqlite database and save it in the FormulaQuestion.txt file, then refreshes the WebControl component which reloads the html file.
Now when the html file is reloaded, the JavaScript should read the text file and display it on alert() which once the alert is able to display the file content, i will then set it to a paragraph and remove the alert().
Please someone should help me out.
Browsers by design do not allow access to the file system for JavaScript, as allowing such access would be a serious security concern.
To provide the FormulaQuestion.txt file to your script you will need to host the file on a server and request it via a HTTP request (like with your fetch). The key thing here is that a server is needed to actually transmit the file over the HTTP protocol to your script.
If working locally, there are many options for running a local server.
The npm serve module,
Wamp
Apache
You may also want to try out some free tier services like Vercel or Netlify. Both I believe allow you to just drag/drop a file and it will host it for you.

Is it possible to block browser access to a text file, but still allow JavaScript access?

The following code, located inside of an HTML file, reads the contents of a local .txt file into a Javascript string variable:
<script>
window.onload=function(){
var allText;
readTextFile("/files/Textfile.txt");
function readTextFile(file)
// https://stackoverflow.com/a/14446538/8840617
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
}
}
</script>
The JavaScript code continues to parse this text to extract a specific substring from allText, and then finally this substring is shown to the user in the HTML.
The problem is that any visitor can find the text file's path by clicking "View Source" in their browser, and then they can navigate to the text file in their browser to see the file in full.
I do not want anyone to be able to see the complete contents of this text file.
So, is it possible to prevent visitors from viewing the .txt file, while still allowing my .html webpage to import the data from the .txt file as a string?
If it is not possible, how should I accomplish this effect, exactly?
No - that's an attempt at a security through obscurity model and not a very obscure one. You can't trust the client or hide information from it. If a script can see it, a malicious or inquisitive user can see it too.
The solution is to expose on your server what someone should be able to see and no more. If the content is private for specific users, you'll need to setup some kind of login and authentication when they request it.

How do I read a local text file?

I want to read a local text file automatically whenever my webpage is opened on my computer. How can I do this? I used the following code from one of solutions answered on this site and it says "Access is denied".
<script type="text/javascript">
var fileDisplayArea = document.getElementById('fileText'); //to show output
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;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///Location/fileToBeRead.txt");
</script>
Is there any other solution to this problem?
You cannot read file off a persons local machine.
You can only read files from the same domain that your site is running on (or if using jsonp to get past XSS rules)
You might be able to use the Local Storage feature of HTML5 to do this.
For security, natively there's no method to read system files (from URL... file:///...).
You should not be reading files on a client machine. Its a security issue and hence not allowed (access denied).
If you want to store data on client machine use cookies rather or as correctly pointed out use a html session or local storage.

read file from local storage using js

hi i'm using java script to read txt file from my pc.
i try to do it in 3 ways like that:
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;
console.log(allText);
}
}
}
rawFile.send(null);
}
console.log("1");
readTextFile("text.txt"); //GOOD
console.log("2");
readTextFile("D:/Documents/Documents/Aptana Studio 3 Workspace/Yonit_web_services/test/text.txt"); //BAD
console.log("3");
readTextFile("file:///D:/Documents/Documents/Aptana Studio 3 Workspace/Yonit_web_services/test/text.txt"); //BAD
all of them are pointing at the same file
i got an error like that:
XMLHttpRequest cannot load file:///D:/Documents/Documents/Aptana%20Studio%203%20Workspace/Yonit_web_services/test/text.txt. Cross origin requests are only supported for HTTP. test.html:21readTextFile test.html:21(anonymous function) test.html:26
whay is that ? thanks.
I had the same problem a while back. I fixed it by opening Chrome through Windows command prompt with this parameter: --disable-web-security
Please note that this has security vulnerabilities.
Browser does not allow to file access through javascript due to security reasons, find the link below.
Security
But in HTML5 its possible via using File Upload/ Download, link
File Uplaod/Download
The first method of reading the file:
readTextFile("text.txt"); //GOOD
is working because "text.txt" is a relative path in the same respect that if you had the file system:
\index.html
\img\img.png
img.png would be accessible to index.html in this respect you might be able to access files and folders in parent and parrent's parent directories by using relative path-ing.
from a windows command prompt you can test these relative paths with dir as follows:
REM Dir will show contents of current directory
Dir
REM Dir .. will show contents of parent directory
Dir ..
REM Dir ../.. will show contents of parent's parent directory
Dir ../..
the same path-ing should work in JavaScript
This being said, the restrictions on d:/ and file://D:/ are most likely for security reason. You might want to check out http://en.wikipedia.org/wiki/Samba_%28software%29 for more details.
You Can always do one thing and that is put it on some url from where your application access it(only if it does not contain any secure information).

Javascript - reading in a file and iterating over sentences

I'm trying to read in a local text file to perform functions like counting syllables, characters etc.,
I am trying to do this by doing:
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "file://path/to/my/file.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
//lines = txtFile.responseText.split("\r\n"); // Will separate each line into an array
} //"\r\n"
}
}
when I try to log 'txtFile' to the command line it prints [ObjectHtmlRequest], how do i look at what i'm loading and consequently iterate over it?
I also get an error message when i try doing this piece of code
var text = txtFile
//$(this).val();
//document.text_input.my_text.value = newtext;
var words = new Array(text.replace(/\s/g, ' ').split(' '));
which worked before, but i'm guessing it's not now because i'm no longer working with text
Most browsers won't allow JavaScript to use the local filesystem. Chrome definitely won't, I'm not sure about Firefox and the others.
What I do in that case is either :
Use a local web server based on the local directory if the file you want to read is static. I usually start it with python -mhttp.server (Python 3) or python -mSimpleHTTPServer (Python 2).
Use the latest HTML5 File API if you want to let the user choose the file. More information here.
EDIT: Well, what I said isn't entirely true. Chrome allows you to use local files, but you have to start it on the command line with a special switch (--allow-file-access-from-files), and frankly, it's a bother and is only really intended for development. Don't rely on it for anything in production!

Categories

Resources