Open a local file from a local page using javascript FileReader - javascript

Is it possible to open a local file from a local page using FileReader without the <input type=file id=files>
The file is in the same directory as the page on a local machine.
reader = new FileReader();
reader.readAsText("output_log.txt");

I have created a sample code using Jquery/javascript which will read a local text file and display its content in Html page
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#fileinput").on('change',function(evt){
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
$("#filename").html(f.name);
$("#fileType").html(f.type);
$("#display_file_content").html(contents);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
});
});
</script>
</head>
<body>
<label>Please upLoad a file</label>
<input type="file" id="fileinput" />
</br>
<div>
<b>File Name:-</b><label id="filename"></label> </br>
<b>File Type:-</b><label id="fileType"></label></br>
<b>Content<b/>
<pre id="display_file_content">
</pre>
<div>
</body>
</html>

Related

How to get the text from a csv file in vanilla javascript

I have an input tag:
<input type="file" id="fileUpload" accept=".csv"/>
that gets a csv file from the user. I then store the file into a variable as such:
const csvFile = document.getElementById('fileUpload');
How can I get the contents of the file into one big string if possible?
You can use the FileReader to read files.
<input type="file" id="fileUpload" accept=".csv" onchange="open(event)" />
<script>
var open = function(event) {
var input = event.target.files[0]
var readerObj = new FileReader()
readerObj.onload = function() {
var fileText = readerObj.result
//do something with fileText here....
}
readerObj.readAsText(input)
}
</script>

Read file using javascript (file path is Known)

<!DOCTYPE html >
<html>
<head>
<title>Untitled Page</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file">
<script type="text/javascript">
document.getElementById('file').onchange = function(){
// create a new instance of FileReader
var reader = new FileReader();
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < 3; line++){
document.write(lines[line]);
document.write("<br>");
}
};
reader.readAsText(file);
};
</script>
</body>
</html>
this is the code I used to read text file using given as a input. Without given as a input I want to read file which already know path.(eg: "index.html") .How could I want to change this code..

To display text from a txt file using javascript

How to read text from a txt file with one button to browse the file and other button to display text. Pls help me in getting the code. i have tried many codes but othing worked. some code was like this. Thanks in advance
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "#":
output=output.split("\n").filter(/./.test, /\#/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>
You should properly read an article like this: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Dont think this line is working properly:
output=output.split("\n").filter(/./.test, /\#/).join("\n");
Try changing it to:
output=output.split("\n").filter(function(l) {
//return /^\#/.test(l); // Starting with #
return l.indexOf('#') > -1; // Containing #
}).join("\n");
It would be interesting to see if this would work as well:
output=output.split("\n").filter(/\#/.test.bind(/\#/)).join("\n");
The second arguments passed to the .filter method is the context:
array.filter(callback[, thisObject])
Get the input file, use FileReader() to read it,on file load get text that matches the pattern. Finally display it through "main" div. Should work..
HTML :
<input id="fileInput" type="file"/>
<div id="main"></div>
jQuery :
$(function(){
$("#fileInput").change(function(e){
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output=output.split("\n").filter(/./.test, /\#/).join("\n");
$("#main").text(output);
};
reader.readAsText(myFile)
});
}
)
Demo

Get text file content using javascript

I've tried use javascript to open text file and get his name and his content, so right now I'm stuck at string, because I used input - type file to get directory / path.
Anyway, my question what is wrong in the next code, and how can i get text file content using javascript?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Display Text Files</title>
<script type="text/javascript">
var str = document.getElementById('txt').value;
function display() {
if (str != "") {
var filename = str.split("/").pop();
document.getElementById('filename').innerHTML = filename;
}
}
</script>
</head>
<body>
<form method="get" action="#" >
<input type="file" accept="text/plain" id="txt" />
<input type="submit" value="Display Text File" onclick="display();" />
</form>
</body>
</html>
EDIT: I also wanna disable in input file the all files opition (*) to text files only (.txt).
Thanks!
Modern browsers implementing FileReader can do this. To test your browser check if window.FileReader is defined.
Here is some code I wrote only this morning to do just this. In my case I simply drag a file onto the HTML element which is here referenced as panel.in1 but you can also use <input type="file" /> (see the reference below).
if (window.FileReader) {
function dragEvent (ev) {
ev.stopPropagation ();
ev.preventDefault ();
if (ev.type == 'drop') {
var reader = new FileReader ();
reader.onloadend = function (ev) { panel.in1.value += this.result; };
reader.readAsText (ev.dataTransfer.files[0]);
}
}
panel.in1.addEventListener ('dragenter', dragEvent, false);
panel.in1.addEventListener ('dragover', dragEvent, false);
panel.in1.addEventListener ('drop', dragEvent, false);
}
It is the reader.onloadend function which gets the text of the file which you recover in the event handler as this.result.
I got most of the mechanism on how to do this from MDN : https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

get the data of uploaded file in javascript

I want to upload a csv file and process the data inside that file. What is the best method to do so? I prefer not to use php script. I did the following steps. But this method only returns the file name instead of file path.So i didnt get the desired output.
<form id='importPfForm'>
<input type='file' name='datafile' size='20'>
<input type='button' value='IMPORT' onclick='importPortfolioFunction()'/>
</form>
function importPortfolioFunction( arg ) {
var f = document.getElementById( 'importPfForm' );
var fileName= f.datafile.value;
}
So how can i get the data inside that file?
The example below is based on the html5rocks solution. It uses the browser's FileReader() function. Newer browsers only.
See http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
In this example, the user selects an HTML file. It is displayed in the <textarea>.
<form enctype="multipart/form-data">
<input id="upload" type=file accept="text/html" name="files[]" size=30>
</form>
<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea>
<script>
function handleFileSelect(evt) {
let files = evt.target.files; // FileList object
// use the 1st file from the list
let f = files[0];
let reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
jQuery( '#ms_word_filtered_html' ).val( e.target.result );
};
})(f);
// Read in the image file as a data URL.
reader.readAsText(f);
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>
you can use the new HTML 5 file api to read file contents
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
but this won't work on every browser so you probably need a server side fallback.
The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.
function init() {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event) {
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>
There exist some new tools on the blob itself that you can use to read the files content as a promise that makes you not have to use the legacy FileReader
// What you need to listen for on the file input
function fileInputChange (evt) {
for (let file of evt.target.files) {
read(file)
}
}
async function read(file) {
// Read the file as text
console.log(await file.text())
// Read the file as ArrayBuffer to handle binary data
console.log(new Uint8Array(await file.arrayBuffer()))
// Abuse response to read json data
console.log(await new Response(file).json())
// Read large data chunk by chunk
console.log(file.stream())
}
read(new File(['{"data": "abc"}'], 'sample.json'))
Try This
document.getElementById('myfile').addEventListener('change', function() {
var GetFile = new FileReader();
GetFile .onload=function(){
// DO Somthing
document.getElementById('output').value= GetFile.result;
}
GetFile.readAsText(this.files[0]);
})
<input type="file" id="myfile">
<textarea id="output" rows="4" cols="50"></textarea>
FileReaderJS can read the files for you. You get the file content inside onLoad(e) event handler as e.target.result.

Categories