I have a small html file that is supposed to display the contents of a text file onto the screen. The text (values.txt) is in the same file as the html file. It appears that when it reads the contents it doesn't get the values as they don't appear in the alert.
here is the code
<html>
<head>
<!--<input type="file" id="fileinput" />-->
<script type="text/javascript">
function readSingleFile(file) {
var f = new File([""], "filename.txt", {type: "text/plain"})
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split(' ');
alert(words[0] + 'test'); //this alert goes off but no values from words[0] are displayed
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
//readSingleFile('values.txt');
</script>
</head>
<body onload="readSingleFile('values.txt')">
</body>
</html>
what can I do in order to read a text file into a list / get this code snippet to work?
The main problem is that first of all you need to get the file for your function. Just passing the file's name as argument is not enough.
Also is better to use an input of type file instead body with an onload attribute.
I've refactored your code in order to get it works.
1. Use this on your Html and delete body onload attribute.
<input id="inp" type="file" />">
Add this function to an external js file or wrap it between script tag inside your html file.
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
alert( "Got the file.n"
+"name: " + f.name + "n"
+"type: " + f.type + "n"
+"size: " + f.size + " bytesn"
+ "starts with: " + contents.substr(1, contents.indexOf("n"))
);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
// this parts gets the file and keeps an eye for changes
document.getElementById('inp').addEventListener('change', readSingleFile,false);
I hope you may find this useful.
Unfortunately I did'nt get it to work with your approach either. As Antonio682 suggested, it would be better to do it with an input-field, but you may aswell try it with an ajax-call :
<html>
<head>
<!--<input type="file" id="fileinput" />-->
<script type="text/javascript">
function readSingleFile(file) {
var objXMLhttp = new XMLHttpRequest()
objXMLhttp.open("GET", file, true);
objXMLhttp.send();
objXMLhttp.onreadystatechange = function(){
if (objXMLhttp.readyState == 4){
if(objXMLhttp.status == 200) {
var arrContents = objXMLhttp.responseText.split("\n");
console.log(arrContents);
} else {
console.log("error");
}
}
}
}
</script>
</head>
<body onload="readSingleFile('values.txt')">
</body>
</html>
You might want to test it with Firefox, since Chromes security settings dont allow file-protocol requests.
You can read more about ajax calls here
Related
Im trying to create an automated system for HTML page handling where I will be able to change the contents
of a<div> inside <body> by writing into an external .txt file and uploading it to the server. Im still an early student in university
and I havent learned PHP and JQuery yet. So I am trying to accomplish this by using only Javascript and HTML.
I just need a way for whatever I write inside the .txt file to be written again inside the <div class="CONTENT" id="target"> which is inside the <body> automatically. Any thoughts and suggestions are greatly appreciated!
You can solve your problem by using the FileReader.
Have a look to
this answer.
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function (e) {
var contents = e.target.result;
displayContents(contents);
};
reader.readAsText(file);
}
function displayContents(contents) {
var element = document.getElementById('target');
element.textContent = contents;
}
document.getElementById('file-input')
.addEventListener('change', readSingleFile, false);
<html>
<head></head>
<body>
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<div id="target" class="CONTENT"></div>
</body>
</html>
You can make an AJAX call for the text file and take the response from that call and set that as the .textContent of the div. Here's an example (see comments inline):
const output = document.getElementById("output");
// Create XHR object
var xhr = new XMLHttpRequest();
// Configure the request (substitute a URL
// to the file below)
xhr.open("GET", filePathHere, false);
// Set up the callback for when the response has
// been recieved
xhr.onreadystatechange = function (){
if(xhr.readyState === 4) {
// Was the request successful?
if(xhr.status === 200 || xhr.status == 0) {
// Populate the <div> with the response text
output.textContent = xhr.responseText;
}
}
}
xhr.send(null); // Make the call
<div id="output"></div>
I'm doing upload multiple files(use <input type="file" multiple/>) with preview image file and can remove the image preview and filedata successfully.
but the problem is, I cannot change the selector for onclick to remove filedata.
(If I change to other selector, it will only remove the preview image but the files still be uploaded to my folder)
The selector for click to remove that work successfully is .selFile but when
I want to change selector for onclick to .selFile2 it will not remove filedata)
these are my focus line of code. (To see my Full code, Please look on bottom)
var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile'
title='Click to remove'> <span class='selFile2'>" + f.name + "</span><br clear=\"left\"/></div>";
..
I change from
$("body").on("click", ".selFile", removeFile);
to
$("body").on("click", ".selFile2", removeFile);
but it remove preview image only not remove filedata (it's still be uploaded to my folder)
..
And I try to change code in function removeFile(e)
from var file = $(this).data("file"); to var file = $('.selFile).data("file"); the result is It can remove only 1 filedata.
...
How could I do?
Here is my full code (2 pages)
firstpage.html (I use ajax to post form)
<!doctype html>
<html>
<head>
<title>Proper Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom:10px;
cursor:pointer;
}
</style>
</head>
<body>
<form id="myForm" method="post">
Multiple Files: <input type="file" id="files" name="files[]" multiple><br/>
<div id="selectedFiles"></div>
<input type="submit">
</form>
<script>
var selDiv = "";
var storedFiles = [];
$(document).ready(function() {
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFiles");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".selFile", removeFile);
});
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
filesArr.forEach(function(f) {
if(!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile' title='Click to remove'> <span class='selFile2'>" + f.name + "</span><br clear=\"left\"/></div>";
selDiv.append(html);
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files[]', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
function removeFile(e) {
var file = $(this).data("file");
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
</script>
</body>
</html>
..
upload.php page
<?php
for($i=0;$i < count($_FILES["files"]["name"]);$i++)
{
if($_FILES["files"]["name"][$i] != "")
{
$tempFile = $_FILES['files']['tmp_name'][$i];
$targetFile = "upload/". $_FILES["files"]["name"][$i];
move_uploaded_file($tempFile,$targetFile);
}
}
?>
It is because when the browser listens to the click event for a .selFile2 element, the img tag becomes the sibling of the event.target (the .selFile2).
Once you delegate the click events to the span tags, $("body").on("click", ".selFile2", removeFile);
You just need to modify your removeFile function a little bit like below.
function removeFile(e) {
var img = e.target.parentElement.querySelector("img");
var file = img.getAttribute('data-file');
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
I have just tested the code and and it is working on my end.
I have a text file that is being updated regularly and I want to know if it is possible to read the file, line by line, with javascript and save the values in variables and then update the html page with the new values every time the page is loaded. The html page is a simple page to display information at work, not a live web page, and does not require any user input other than just navigating between the two pages. The text file is on a network drive that everyone has access to. Here is an example of what I'm trying to accomplish:
var value1;
var value2;
Read the file with javascript if possible and extract data and assign to value1 and value2.
document.getElementsByClassName("class for <p>")[0].innerHTML = value;
document.getElementsByClassName("class for another <p>")[0].innerHTML = value;
I have googled this but was not able to find anything that worked. If this is not possible with JS, any suggestions on how this can be done differently. Thanks in advance.
At first, you need to use a input[type=file] to get a File.
<input type=file id=file/>
<div id=result></div>
And then use FileReader to read file to target format, just like base64, text, buffer.
const file = document.getElementById('file').files[0]
const result = document.getElementById('result')
const reader = new FileReader
reader.addEventListener('load', () => {
result.innerHTML = reader.result
})
reader.readAsText(file, 'UTF-8')
See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
You could use the javascript FileReader and input type="file" to read the local files in your machine. Please see the below attached code for example.
<!DOCTYPE html>
<html>
<head>
<script>
function OnFileLoad() {
var file = document.getElementById("FileReader").files[0];
var textType = /text.*/;
var fileDisplayArea = document.getElementById("FileContent");
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function (e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
}
</script>
</head>
<body>
<input type="file" id="FileReader" onchange="OnFileLoad()" />
<div id="FileContent">Your content will appear here</div>
</body>
</html>
In order to specify the file path you might need to have a server as well. I have attached a sample code here with. You can find the details regarding Specifying the file path here and issues that will happen to read file without a server here
<!DOCTYPE html>
<html>
<head>
<script>
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
var fileDisplayArea = document.getElementById("FileContent");
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText;
}
} else {
fileDisplayArea.innerText = "File not supported!"
}
}
rawFile.send(null);
}
readTextFile("file:///C:/Users/t0423/Desktop/test.js")
</script>
</head>
<body>
<div id="FileContent">Your content will appear here</div>
</body>
</html>
I have a <textarea> element and a button that calls a loadFile() JavaScript function. I want this function to allow me to load the text from a .txt file on my local machine into the textarea. Any help with this would be greatly appreciated!
You can use the File and FileReader objects to read local files.
You can use an input element with type="file" to allow the user to select a file.
<input id="myFile" type="file"/>
<textarea id="myTextArea" rows="4" columns="20"></textArea>
After the user has selected a file, you can get the File object from the input element. For example...
var file = document.getElementById("myFile").files[0];
You can then use a FileReader object to read the file into the text area. For example...
var reader = new FileReader();
reader.onload = function (e) {
var textArea = document.getElementById("myTextArea");
textArea.value = e.target.result;
};
reader.readAsText(file);
I found a old topic about this:
How do I load the contents of a text file into a javascript variable?
Have you read the last answer already? This works with a div instead of a textbox, but you could adapt the code a bit.
In the last piece of the last commenters post you could change this line:
document.getElementById("id01").innerHTML = out;
to:
document.getElementById("textbox01").innerHTML = out;
And in your HTML:
<textarea name="textbox01">Enter text here...</textarea>
Result:
function loadFile() {
var xmlhttp = new XMLHttpRequest();
var url = "file.txt";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
console.log("xmlhttp Request Asepted");
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
var row = 0;
for(i = 0; i < arr.length; i++) {
// console.log( arr[1].data); change data to what every you have in your file
// out += arr[i].data + '<br>' + arr[i].data2 ;
document.getElementById("textbox01").innerHTML = out;
}
}
}
The code below is to read a text file using javascript. it works.
However, I just want to read part of the content.
For example, the content of the file is :"Hello world!"
I just want to display "Hello".
I tried function split(), but it only works on strings. I don't know how to insert it here.
var urls = ["data.txt"];
function loadUrl() {
var urlToLoad = urls[0];
alert("load URL ... " + urlToLoad);
browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}
thank you!!!
I used
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
, and got data from my text file.
Or try this
JQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.
Untested, but the general gist of it...
var HTML_FILE_URL = '/whatever/html/file.html';
$(document).ready(function() {
$.get(HTML_FILE_URL, function(data) {
var fileDom = $(data);
fileDom.find('h2').each(function() {
alert($(this).text());
});
});
});
Try this to read separate words if I understood correctly what you need.
Create a file with the contents "hello world" and browse to it with the example script.
The output is "hello".
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split(' ');
alert(words[0]);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</head>
<body>
</body>
</html>
Reading directly has to be with an ajax request due to the javascript restrictions regarding safety.
This code shoudl perform the requested operation:
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState==4){
var words = xmlhttp.responseText.split(' ');
alert(words[0]);
}
}
xmlhttp.open("GET","FileName.txt",true);
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
Opening a file in javascript with ajax (without using any framework)
var urls = ["data.txt"];
xhrDoc= new XMLHttpRequest();
xhrDoc.open('GET', urls[0] , async)
if (xhrDoc.overrideMimeType)
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
var data= this.response; //Here is a string of the text data
}
}
}
xhrDoc.send() //sending the request