How to read the first line of .txt file? - javascript

can anyone one help how to read the first line of .txt file? I have input type file that upload example.txt then I would like to grab the first line from that code. I tried something like this:
<input type="file" id="fileUpload" name="fileUpload"/> MyTest.txt //file name
function confirmFileSubmit(){
var fileName = $('#fileUpload').val();
alert($('#fileUpload').split('\n')[0]);
}
After I run my code this just outputted file name in alert box. I'm not sure how I can read the content of the file. If anyone can help please let me know.

You'll need the FileReader for that
function confirmFileSubmit(){
var input = document.getElementById('fileUpload'); // get the input
var file = input.files[0]; // assuming single file, no multiple
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result; // the entire file
var firstLine = text.split('\n').shift(); // first line
console.log(firstLine); // use the console for debugging
}
reader.readAsText(file, 'UTF-8'); // or whatever encoding you're using
// UTF-8 is default, so this argument
} // is not really needed

Related

Loading and Reading text file onto HTML/JavaScript

I am trying to read and load a locally stored text file (it's saved on the user's computer, but may be moved to a local directory) into a variable or array so that I can generate a table with it in HTML.
I have found a way to have the user select and upload the file, but the code displays the text on the browser. I want it stored so I can manipulate the data so that I can put it in the correct row and cell. I know how to create a table, format it, format and splice text and things similar to that.
The code, which I found here but forgot which specific ask it was, goes as follows
<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>
For reference, here's a sample of the text file and here's what I want.
I am still relatively new to HTML and Javascript, but eager to learn. Anything will be appreciated.
You already have some parts working:
You have found a way to have the user select and upload the file
You know how to create a table, format it, format and splice text and things
Now we need to connect these things. Unfortunately, now all the script does is display the text on the browser when the user loads a text file. This is the part of the code responsible for that:
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
It displays it inside the <pre id="fileDisplayArea"><pre> area of your html. You want to store it inside a variable, so you can start to create a table, format it, format and splice text and things (the part 2 you already know):
reader.onload = function(e) {
myTextToFormat = reader.result;
// start formatting and make it into a table...
}

How to read local files using HTML 5 FileReader? [duplicate]

This question already has answers here:
Javascript read file without using input
(3 answers)
Closed 6 years ago.
Objective
I am making an application, and I need to read a local file using JavaScript and HTML 5, without any <input> tags or user interaction whatsoever.
What I tried
On my research, I found two tutorials that are heavily cited in SO:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
However, there is a problem. Both of this tutorials require user interaction via the input tag, which is a life killer since I want to read the contents of the file automatically into a string.
Code
So far I managed to get the following code:
let readFile = function(path) {
let reader = new FileReader();
reader.onload = function(e) {
var text = reader.result;
console.log(text);
};
// Read in the image file as a data URL.
reader.readAsText(MissingFileHandle);
};
But as you can see, I am missing an important step, I am missing MissingFileHandle. My idea would be to pass a path to this method, and so the method would read the file locally as text and print it into the console, but I am unable to achieve this.
Question
Given a relative path, how can I read the contents of a file using HTML 5 without using <input> tags?
The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.
Is it possible to load a file with JS/HTML5 FileReader on non served page?
How to open a local disk file with Javascript?
How to set a value to a file input in HTML?
Javascript read file without using input
These links help you to find answer.
This Can do a trick.
HTML
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
JS
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!"
}
});
}

Parsing an existing text file with no user selection

Long story short, I am looking to parse a text file (eventually kept on a server, but for now tested locally) that will update content, but will never change file location, name or extension.
Let's say the file is called feed.txt in C:\files. So, I always want my parser to traverse through the static C:\files\feed.html.
I know am all familiar with
<input type="file" name="file" id="file">
for user selection, but I want my javascipt parser to skip that all together, grab the file, parse it as such:
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
reader.readAsText(file);
};
and have certain strings being displayed back into my html (code not written yet - still on the parsing part). How do I go about skipping user file selection and just having the javascript know which file (and where) to parse?
Thanks!

How to convert a PDF file into a base64 string in java script

I have created an app in sencha touch cordova, and in my app I have a functionality to download PDFs.
I have successfully downloaded a pdf file, but now I want to convert the PDF into a base64 string using JavaScript.
Can anybody tell me how to do it?
See if your JavaScript environment has the "atob" and "btoa" functions available:
var encodedData = window.btoa("Hello, world"); // encode a string
var decodedData = window.atob(encodedData); // decode the string
These convert a string to and from Base64 encoding.
Trying using the logic below.
<input id="inputFile" type="file" onchange="convertToBase64();" />
function convertToBase64(){
//Read File
var selectedFile = document.getElementById("inputFile").files;
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
var fileToLoad = selectedFile[0];
// FileReader function for read the file.
var fileReader = new FileReader();
var base64;
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
// Print data in console
console.log(base64);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
}
Note : This snippet was taken from stackoverflow, but I dont remember the link :(

Convert image from readAsDataURL to readAsBinaryString

Using the filereader API it is possible to show a preview of the file, by reading the file with readAsDataURL
What I am trying to do is:
The user selects a file
A preview is shown, so that the user has some feedback.
If the user is satisfied, he submits the data to the backend.
Implementing step 3 can be done by re-reading the file with readAsBinaryString, but this looks problematic because the data could have disappeared or changed on disk. So What I would like is to convert the data returned from readAsDataURL to the format returned by readAsBinaryString. How can I do this?
Another alternative would be to submit the data to the backend as returned by readAsDataURL, but I would like to avoid that, since that would require special handling on the backend in my case.
Like CBroe said, you dont need to read the file twice.
JS :
handleFileSelectThumbFile(evt){
var files = evt.target.files;
var file = files[0];
// You can get the mime type like this.
var thumbMIME = files[0]['name'].split('.').pop();
if (files && file) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
// Split the readerEvt.target.result by a ','.
// You can send the binaryString variable to the server.
// Its base64 encoded already.
var binaryString = readerEvt.target.result.split(',')[1];
// Set the image preview to the uploaded image.
$('.img-preview').prop('src', readerEvt.target.result);
}.bind(this);
reader.readAsDataURL(file);
}
}
HTML :
<input type="file" onChange={this.handleFileSelectThumbFile} required/>
<img src='http://placehold.it/300' class='img-preview'/>
You can read the MIME type from the first part of readerEvt as well. Look at CBroe's comment above.

Categories