Reading uploaded text file contents in variable - javascript

I want to read string from text file and save it in variable . What I did:
HTML:
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
JS:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
var newString;
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;
}
newString=reader.result; //SAVE RESULT
alert(newString);
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
I want to save text from file and alert it. But it doesnt work.
I did it:
var tfile;
var reader = new FileReader();
function rdfile(files)
{
tfile = files[0];
reader.readAsText(tfile, 'CP1251');
reader.onload = function(e)
{
str = e.target.result;
alert(str);
};
}
But it doesnt work too. I alert many different symbols but not my text.

Look at your code from your first attempt:
newString=reader.result; //SAVE RESULT
alert(newString);
reader.readAsText(file);
Get the result
Alert it
Do the thing that generates the result
You have to read the file before you can look at the text you get from reading it!
Move steps 1 and 2 in to the onload event handler you already have.
Now look at your second attempt. You never call rdfile and you never call readAsText.

Related

Is there a way to pull data from a txt file and make it update everytime the txt file is updated?

Is there a way to pull data from a txt file and make it update everytime the txt file is updated? I'm using the following code in my program and it will find the file and display its content fine but when I update the txt file, the program does not update the new text.
function OnFileLoad()
{
var file = document.getElementById("FileReader").files[0];
var fileDisplayArea = document.getElementById("FileContent");
if (file.type.match('text.*|image.*|application.*'))
{
console.log('hello. we are inside the function')
var reader = new FileReader();
reader.onload = function (e)
{
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
}
else
{
fileDisplayArea.innerText = "File not supported!"
}
}

How to submit base64 string of an uploaded image using only jquery

Here are the jquery codes that i've written
$(function(){
// Prepare the preview for profile picture
$("#profile_image").change(function(){
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#wizardPicturePreview1').attr('src','/images/houses/default.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = function (e) {
$('#wizardPicturePreview1').attr('src', e.target.result).fadeIn('slow');
//getting the base64 string of the uploaded image
var imageso = e.target.result;
console.log('Encoded image:', imageso);
};
reader.readAsDataURL(this.files[0]);
}
});
$('form').submit(function() {
// submit the encoded base64 string of the uploaded image
$('.hidden-image-data').val(imageso);
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return true;
});
});
I am getting the encoded image in console with the imageso variable in the change() function but it is nullable In the submit() function, the console tells me that the imageso variable is not declared while it is already declared. The problem is, how to get that base64 string of the uploaded image in the submit funtion using only JQuery without using Ajax?
imageso is outside the scope of the submit handler, you won't be able to access the variable as a result.
You will have to bring imageso into the submit scope.
I'd recommend to try and store it in the sessionStorage:
$(function(){
// Prepare the preview for profile picture
$("#profile_image").change(function(){
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#wizardPicturePreview1').attr('src','/images/houses/default.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = function (e) {
$('#wizardPicturePreview1').attr('src', e.target.result).fadeIn('slow');
//getting the base64 string of the uploaded image
var imageso = e.target.result;
sessionStorage.setItem("imageso", imageso);
console.log('Encoded image:', imageso);
};
reader.readAsDataURL(this.files[0]);
}
});
$('form').submit(function() {
// submit the encoded base64 string of the uploaded image
$('.hidden-image-data').val(sessionStorage.getItem("imageso"));
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return true;
});
Thx Saravenan N, i've found the answer. Declare imageso after the document ready function
$(function(){
var imageso;
// Prepare the preview for profile picture
$("#profile_image").change(function(){
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#wizardPicturePreview1').attr('src','/images/houses/default.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = function (e) {
$('#wizardPicturePreview1').attr('src', e.target.result).fadeIn('slow');
//getting the base64 string of the uploaded image
imageso = e.target.result;
console.log('Encoded image:', imageso);
};
reader.readAsDataURL(this.files[0]);
}
});
$('form').submit(function() {
// submit the encoded base64 string of the uploaded image
$('.hidden-image-data').val(imageso);
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return true;
});
});

Turning a html File (API Type) instance into a string?

With the HTML File API we can get a file selected via an <input type="file"> element with var file = evt.target.files[0];.
How do we get the file content as a string (Something like var content = file.toString().
I currently have this code which gets triggered by the input element.onchange event:
input.onchange = function handleFileSelect(evt) {
var file = evt.target.files[0];
var reader = new FileReader();
console.log("RAW FILE: ", file);
var string = reader.readAsText(file);
console.log("FILE CONTENT: ", string);
}
When I select a file I try to log the contents this happens:
RAW FILE: File
bundle.js:5293 FILE CONTENT: undefined
Thoughts?
Turns out a file cannot just be read synchronously like this:
var reader = new FileReader();
content = reader.readAsText(file);
Before we can read the file we first have to attach to the onload event on the file reader.
reader.onload = (e) => {
let content = e.target.result;
console.log("FILE CONTENT: ", content);
}
The trigger the file read:
reader.readAsText(file);
The content will now contain the file content.

dataURL does not work for <a>

update: Finally I find out the reason myself, the reason is: actually I used Angular's ng-href at the same time, which prefix a unsafe to the data url, I have to config the compiler service to waive that restriction like:
.config( [
'$compileProvider',
function( $compileProvider )
{
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension):/);
// Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
}
])
Which talks about here:
Angular changes urls to "unsafe:" in extension page
All:
What I want to do is read in a image as dataURL and give it to a tag as download:
<input type='file' name='doc' />
Download
<script>
var fileOBJ = $("input")[0]
.files[0];
var reader = new FileReader();
reader.onload = function(e){
$("a")[0].href=e.target.result;
}
reader.onerror = function(err){
console.log(err);
}
reader.readAsDataURL(fileOBJ);
</script>
The download always failed.
But if I use a <img> instead of <a>, then the image can shown up. I do not know what is wrong with the <a> link
Specify the atrribute download on the link. Like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='file' name='doc' />
<a download="filename" href="#">Download</a>
<script>
$("input").change(function() {
var fileOBJ = $("input")[0]
.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$("a")[0].href = e.target.result;
// if you want to change the download filename
// $($("a")[0]).attr("download", "some other filename");
}
reader.onerror = function(err) {
console.log(err);
}
reader.readAsDataURL(fileOBJ);
})
</script>
You try to call readAsDataURL when there is any file selected, what throws an error. Use this method after you select some file.
var reader = new FileReader();
reader.onload = function(e){
$("a")[0].href = e.target.result;
};
reader.onerror = function(err){
console.log(err);
};
$('#inpFile').on('change',function(){
reader.readAsDataURL(this.files[0]);
});

Read CSV file with Javascript into a key value pair array

There are plenty of examples of reading a CSV file using jQuery however javascript examples are few and far between.
As i am using an internal script editor for a particular application, i am limited to using Javascript only.
I have a csv file that has headings followed by data in each row.
Heading1,Heading2,Heading3,Heading4
row1data1,row1data2,row1data3,row1data4
row2data1,row2data2,row2data3,row2data4
The delimiter being used is , however there could be others e.g. ^.
As i can't upload a file, i have the option to manually reference an absolute path.
Is there a way i can use only javascript to read a csv file?
As a start, here is a couple of ways to read a file with javascript
HttpRequest: (from web server or absolute path)
Source: Javascript - read local text file
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
And specify file:// in your filename when using an absolute path
readTextFile("file:///C:/your/path/to/file.txt");
FileReader API:
Source:
- http://codepen.io/matt-west/pen/KjEHg
- http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
HTML
<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>
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!"
}
});
}
JS on MS Windows (simple sample)
Source: http://msdn.microsoft.com/en-us/library/czxefwt8(v=vs.84).aspx
function ReadFiles()
{
var fso, f1, ts, s;
var ForReading = 1;
fso = new ActiveXObject("Scripting.FileSystemObject");
ts = fso.OpenTextFile("c:\\testfile.txt", ForReading);
s = ts.ReadLine();
// s holds the text content
ts.Close();
}

Categories

Resources