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).
Related
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.
my company has tasked me with maintaning an internal environment webpage that houses the installers for each of our environments. the format of this location is: Root > webpage.html / EnvFolders > installer.exe / version.txt
the webpage has each environment listed, along with a static link to the sub folder installer file. it also has a line for the version. when we update an environment, neither the installer or version file names change, so the link to the installer never gets out of date. the version is supposed to be manually updated, but most of the time the tech doing the update doesn't, ergo, this post.
i am needing a way to read the single line within the version.txt file and display it in on the correct env. i am looking to have a line of code at each environment listing that then triggers a single function that does the actual work of pulling the data.
i've found this solution which works for a single file, but i need the function to iterate multiple times though different files. i've included the code below that works for a single file.
<span id="placeholder"></span>
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('placeholder').innerHTML = xhr.responseText;
}
}
xhr.open('GET', 'test.txt');
xhr.send();
</script>
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.
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.
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.