I have read some of the previous questions on this topic but I really need to be 100% sure!
Is it possible to read from a .txt file on my local system and present it in my HTML-BODY?
I have tried several functions, here is one:
function readFile (path) {
var fso = new ActiveXObject('Scripting.FileSystemObject'),
iStream=fso.OpenTextFile(path, 1, false);
while(!iStream.AtEndOfStream) {
document.body.innerHTML += iStream.ReadLine() + '<br/>';
}
iStream.Close();
}
readFile("testing.txt");
The content of the file is simply around 100 words I want to read from the text file and display in my HTML-BODY.
Is this possible without having my own server?
You can use a FileReader object to read text file here is example code:
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
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>
Here is the codepen demo
If you have a fixed file to read every time your application load then you can use this code :
<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
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:///C:/your/path/to/file.txt");
</script>
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>
Related
I'm trying to Figure out how to replace HTML text using js code,
the goal of it is the read a "1.txt" file with a name and replace the HTML text (Replace me!!)
if anyone can help me and point me in the right direction.
here is what I have now
<body class="htmlNoPages">
<div id="main"><p>Replace me!!</p></div>
</body>
<script type="text/javascript" id="gwd-init-code">
function load() {
// var text = ('test 123')
var file = new XMLHttpRequest();
file.open(GET,'file:///d:/1.txt', true);
file.responseType =Text;
file.onreadystatechange = function() {
if (file.readyState === 4) { // Makes sure the document is ready to parse
if (file.status === 200) { // Makes sure it's found the file
text = file.responseText;
}
}
}
let element = document.querySelector('#main');
element.innerHTML = text;
}
window.onLoad = load();
</script>
I did it like this
var TxtFile = new XMLHttpRequest();
TxtFile.onreadystatechange = function () {
var allText = "Uw browser is niet compatibel of u heeft uw java script disabeld staan";
if (TxtFile.readyState === XMLHttpRequest.DONE && TxtFile.status == 200) {
allText = TxtFile.responseText;
allText = allText.split("\n").join("<br>");
}
document.getElementById('planning').innerHTML = allText;
}
TxtFile.open("GET", 'File location', true);
TxtFile.send(null);
I currently I have this piece of code which was originally a sample code online but edited slightly to fit my needs.
<input type="file" id="files" name="file" />
<span class="readBytesButtons">
<button>display injected files</button>
<span>
<div id="displayedText"></div>
function readBlob(opt_startByte, opt_stopByte) {
var files = document.getElementById('files').files;
console.log(files);
if (!files.length) {
alert('Please select a file!');
return;
}
//var file = files[0];
var reader = new FileReader();
reader.readAsText(files[0], "UTF-8");
reader.onload = function (evt) {
try {
var startWord = "inject";
var endWord = "];";
var injectedFilesString = evt.target.result.slice(evt.target.result.indexOf(startWord), evt.target.result.indexOf(endWord)) + "]";
var injectedFiles = injectedFilesString.split('[')[1].split(']')[0].split(', ');
document.getElementById("displayedText").innerHTML = injectedFiles
; }
catch(err) {
document.getElementById("displayedText").innerHTML = "<span style='color: red; font-weight: bold; font-family: verdana;'>This file does not have any injected files within it.</span>";
}
}
reader.onerror = function (evt) {
alert("error reading file");
}
}
document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
if (evt.target.tagName.toLowerCase() == 'button') {
var startByte = evt.target.getAttribute('data-startbyte');
var endByte = evt.target.getAttribute('data-endbyte');
readBlob(startByte, endByte);
console.log(files);
}
}, false);
This piece of code currently reads and displays a certain portion of a file which is selected by the file selector tool. How could I change this code so that I don't need the file selector and could print portions of a file using a method such as fileName.injected();
Thanks, let me know if you have any clarifications
I want to count words from below file types..
['pdf','xls','xlsx','odt','ppt','pptx','txt','doc','docx','rtf']/
currently my code reads text files only..
please help me for other file types..
Below is my code..
<script>
$('#file').change( function(event) {
var imgpath=document.getElementById('file');
if (!imgpath.value==""){
var ext = imgpath.value.split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf','xls','xlsx','odt','ppt','pptx','txt','doc','docx','rtf']) != -1) {
var f = event.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var strings = "";
var contents = e.target.result; alert(contents);
var words = contents.match(/\S+/g).length;
$('#display_file_count').text(words);
}
r.readAsText(f);
}
}else{
alert('file type not supported.');
$('#file').val('');
}
}
});
</script>
I am using fileReader for checking if a profile picture uploaded matches with my conditions. However, i don't have always the same result. Can you help me to fix that bug ?
Here my htlm code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File API</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="page-wrapper">
<h1>Image File Reader</h1>
<div>
Select an image file:
<input type="file" id="fileInput">
</div>
</div>
<script src="images.js"></script>
</body>
</html>
Here my javascript/fileReader (images.js) code:
window.onload = function()
{
var width=0;
var height=0;
var exten= false;
var size = false;
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e)
{
var file = fileInput.files[0];
var imageType = /image.png/;
if (file.type.match(imageType))
{
exten = true;
var reader = new FileReader();
reader.onload = function(e)
{
var img = new Image();
img.src = reader.result;
img.onload = function()
{
width=this.width;
height=this.height;
}
}
reader.readAsDataURL(file);
}
else
{
exten= false;
}
if(width == 50 && height ==50)
{
size = true;
}
else
{
size = false;
}
//Here, we check that the image matches with png and 50*50px
if(size && exten)
{
alert('Your image is ok.');
}
else
{
if(!size && !exten)
{
alert('Image needs to be 50*50px and in png');
}
else
{
if(!size && exten)
{
alert('Image needs to be 50*50px');
}
else
{
if(size && !exten)
{
alert('Image needs to be in png');
}
}
}
}
});
}
Thank you for your help
You've to wait the execution of the img.onload event before checking width and height.
The code that's outside that event handler and that uses those properties should be moved inside it.
My html 5 canvas is being saved to a server via php. It also pops up in a new window that is not html. The new window only contains the png image. I would like this new popup window to be able to share to social media. I know about auth2.0 and setting that up. What I don't know is how to get my png created from the saved canvas to popup on a new html page so I can add my social media tools. I am pretty sure it would be an edit to this line, window.open(testCanvas.toDataURL("images/png"));.
function saveImage() {
cursor.visible = false; stage.update();
var canvasData = testCanvas.toDataURL("image/png");
window.open(testCanvas.toDataURL("images/png"));
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
cursor.visible = true; stage.update();
}
else if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.open('POST', 'testSave.php', false);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function() {
console.log(ajax.responseText);
}
ajax.send("imgData="+canvasData);
}
New example without server side (using localStorage)
On the first page:
<input type="file" id="upfile" />
<script>
$ = function(id) { return document.getElementById(id); };
$('upfile').onchange = function(e) {
var files = e.target.files;
for (var i = 0; i < files.length; i++)
{
var f = files[i];
if (! f.type.match('image.*'))
continue;
var reader = new FileReader();
reader.onload = (function(filecontent) {
return function(ev) {
var b64data = ev.target.result;
localStorage.setItem('img', b64data);
window.open('popup.html', 'popup', 'width=600,height=400');
};
})(f);
reader.readAsDataURL(f);
}
};
</script>
In the popup page:
<img src="" id="thepicture" />
<script>
window.onload = function() {
document.getElementById('thepicture').src = localStorage.getItem('img');
};
</script>
Check the working demo here