Read a .txt file and output him in <p> HTML (with JS) - javascript

I have tried a lot of possibilities, but most of them don't work or require modules, but I don't know how to do this in vanilla javascript.. I really need some help.. Thanks. (Sorry for my bad English, I'm french)
My script : (don't really work, just read)
<script type="text/javascript">
var fso, ts, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.OpenTextFile("pub.txt", 1);
s = ts.ReadLine();
</script>

Reading a text file:
fetch('file.txt')
.then(response => response.text())
.then(text => console.log(text))
// outputs the content of the text file
Using Jquery:
$("#div7").load("ajax.txt");

Try this out!
<input type="file" onchange="readFile(this)" />
<script>
function readFile(input) {
let file = input.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function () {
document.getElementById("app").innerHTML = `<p>${reader.result}</p>`;
};
reader.onerror = function () {
console.log(reader.error);
};
}
</script>

document.querySelector("input[type='file']").addEventListener("change", function(){
if(this.files[0]){
this.files[0].text()
.then(val => {
document.querySelector("p").textContent = val;
})
}
})
<label>Pick One Text File</label><br/>
<input type="file" accept="text/plain" multiple="false"> <br/>
<label>File Will Show up here in the text box</label><br/><br/>
<p></p>

Edit: a working example here
https://codepen.io/engeslamadell/pen/WNrVPeG
did you tried this
<script type="text/javascript">
//this is the input with type file
document.getElementById('inputfile')
.addEventListener('change', function() {
var fr=new FileReader();
fr.onload=function(){
document.getElementById('output')
.textContent=fr.result;
}
fr.readAsText(this.files[0]);
})
</script>
you also have these FileReader methods
FileReader.readAsArrayBuffer(): Reads the contents of the specified input file. The result attribute contains an ArrayBuffer representing the file’s data.
FileReader.readAsBinaryString(): Reads the contents of the specified input file. The result attribute contains the raw binary data from the file as a string.
FileReader.readAsDataURL(): Reads the contents of the specified input file. The result attribute contains a URL representing the file’s data.
FileReader.readAsText(): Reads the contents of the specified input file. The result attribute contains the contents of the file as a text string. This method can take encoding version as the second argument(if required). The default encoding is UTF-8.
source: https://www.geeksforgeeks.org/how-to-read-a-local-text-file-using-javascript/

Related

How to guess the encoding when using FileReader.readAsText() in frontend javascript [duplicate]

txt file maybe utf8/GB2312,.... but if upload to my server, i got ascii only. how to detect file encoding, so i can set in readAsText()?
$("#fileinput").change(function(evt){
if (!checkSupport())return;
var f = evt.target.files[0];
if (!f) return;
var r = new FileReader();
r.onload = function(evt){ //file loaded successfuly
g_fname=f.name;
g_contents = evt.target.result;
curpage.val(0);
read_article();
}
r.readAsText(f,'GB2312');
});
As of 2021 I think the easiest solution is to use detect-file-encoding-and-language!
You can simply load it via the <script> tag:
<script src="https://unpkg.com/detect-file-encoding-and-language/umd/language-encoding.min.js"></script>
From the documentation:
// index.html
<body>
<input type="file" id="my-input-field" />
<script src="https://unpkg.com/detect-file-encoding-and-language/umd/language-encoding.min.js"></script>
<script src="app.js"></script>
</body>
// app.js
document.getElementById("my-input-field").addEventListener("change", inputHandler);
function inputHandler(e) {
const file = e.target.files[0];
languageEncoding(file).then(fileInfo => console.log(fileInfo));
// Possible result: { language: english, encoding: UTF-8, confidence: { language: 0.97, encoding: 1 } }
}
I know this is an old post, but since it is unanswered, I'd like to throw this out there to anyone who might be interested:
You should check out this library encoding.js
They also have a working demo. I would suggest you first try it out with the files that you'll typically work with to see if it detects the encoding correctly and then use the library in your project.

How to read and display html file

I'm making a html editor but the problem is that when someone needs to view an html file i don't know how to display the text from the file.
<input type="file" onchange="previewFile()"><br>
<p id="txt1" src="blank.html"></p>
<script>
function previewFile() {
const preview = document.getElementById('txt1');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
// reads image file to a blob string
preview.src = window.URL.createObjectURL(file);
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
</script>
I used this script to read a file and display it by changing the paragraph src to a blob link, but looks like the paragraph dosn't get the text by a html text link using src.
Is there a way to do it?
The paragraph does not have src attribute, You need to use either innerText or innerHTML to display the content.
function previewFile() {
const content = document.querySelector('.content');
const [file] = document.querySelector('input[type=file]').files;
const reader = new FileReader();
reader.addEventListener("load", () => {
// this will then display a text file
content.innerText = reader.result;
}, false);
if (file) {
reader.readAsText(file);
}
}
<input type="file" onchange="previewFile()"><br>
<p class="content"></p>
The p tag does not support src attribute so the alternative solutions would be using element.innerHTML= text or you change the p tag into iframe

Reading the name of a File with Javascript/jQuery

Currently I am making a program in which works as a text editor. I have a section where you can rename the title, and when you save, it takes that document.getElementById('title').innerHTML and makes it the .txt name.
For example:
If the title div had the innerHTML of "Document", the file would be called "Document.txt".
My problem is that I want it to also upload a file and take its file name.
For example:
I uploaded a file called "Document.txt", and the function makes the title "Document". (I am using a .replace('.txt','') to make it not show in the title and a += '.txt' to make the file actually a .txt when saved.
Anyone know how to make the file name of the uploaded document using an <input type='file'> a string to be used elsewhere?
Here is some code to put it in perspective:
var id = function(id){return document.getElementById(id)};
function readText(that)
{
var reader = new FileReader();
reader.onload = function(e)
{
var output = e.target.result,
name = FILENAMEFIND();
id('page').innerHTML = output;
id('title').innerHTML = name;
}
reader.readAsText(that.files[0]);
}
Ok, I figured it out myself:
var id = function(id){return document.getElementById(id)},
input = id("upfile"),
file = input.value.split("\\"),
fileName = file[file.length-1]; // Take purely the file name
id('title').innerHTML = fileName; // Outputted to title div

Generating File object that can be read by javascript FileReader without HTML Input tag

I'm a newbie to dynamic HTML websites so bear with me. This is a locally run webpage for my network only. On load of my webpage, I want it to read a text file and place the data into a textarea. This will then update every couple seconds to display the changes in the text file. I've read several examples on how to do it using the input tag in HTML, but I want it to load without user input.
I'd like to use FileReader() with javascript, but don't know how to make an object that can be read by readAsText(object_here).
<script>
var intervalID1;
function updateTextTimer()
{
intervalID1 = setInterval(updateText,5000);
}
function updateText()
{
var temp = document.getElementById('logOutput');
var reader = new FileReader();
var fileName = "test.txt";
reader.onload = function(e) {temp.value = e.target.result;}
reader.readAsText(file_object);
}
</script>
Again, I'd prefer to use FileReader because it would be easy, but willing to take suggestions. Thanks!
Try using .load()
var timeout = null;
(function loadText() {
$("#logOutput").load("test.txt", function() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(loadText, 5000)
})
}())
e.g.,
var timeout = null, obj = null;
(function loadText() {
obj = URL.createObjectURL(new Blob([$("#input").val()], {
type: "text/plain"
}))
$("#logOutput").load(obj, function() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(loadText, 5000)
})
}())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<label for="input">input text here:</label><br />
<textarea id="input">
</textarea>
<br />
<label for="logOutput">output:</label>
<br />
<textarea id="logOutput" disabled>
</textarea>
readAsText Only accept Blob object, you can ref how to create a Blob OBj.

Read an input tag into a javascript string

I'm trying to read an input type="file" tag into a javascript string. I know this should be simple but I simply cannot get my code to work. The file is plain .html. Here's what I have
<h3>Select location of html file.</h3>
<form onSubmit="submitButtonPressed()">
<input type="file" id="classList" />
<input type="submit" />
</form>
<script>
var reader = new FileReader();
var htmlFile = document.getElementById("classList").files[0]; //read the file selected with the <input> tag
reader.readAsText(htmlFile);
var htmlText = reader.result; //and create a string with the contents
function submitButtonPressed() {
var lengthOfText = htmlText.length;
alert("It is " + lengthOfText + " characters long");
}
</script>
I'm just trying to create a string that contains the contents of the .html file selected by the input tag. I can't figure out why htmlText doesn't contain the contents of the .html file, could someone explain what I'm doing wrong?
this is the right answer for you :
HTML5 File API: How to see the result of readAsText()
reader.onload = function(e) {
// e.target.result should contain the text
};
reader.readAsText(file);
so i guess you will have to check on pressing the button if the file was loaded or not , maybe it is still in progress , or encountered an error

Categories

Resources