How to read and process csv file using javascript and jquery? - javascript

I am struck in a problem where I am trying to read a csv file using Browse button by the following HTML tag:
<input type="file" name="filename" id="filename">
<div id="csvimporthint"></div>
and my jquery code to read and process the input file is as below:
<script>
$("#filename").change(function(e) {
var ext = $("input#filename").val().split(".").pop().toLowerCase();
if($.inArray(ext, ["csv"]) == -1) {
alert('Upload CSV');
return false;
}
if (e.target.files != undefined) {
var reader = new FileReader();
var csvLines;
var csvValues;
var i;
reader.onload = function(e) {
csvLines = e.target.result.split("\n");
for(i=1; i<csvLines.length; i++){
csvValues = csvLines[i].split(",");
importedLat = csvValues[0];
importedLon = csvValues[1];
markerFunc(importedLat, importedLon);
addLayer();
}
//$("#csvimporthint").html(importedLat + " " + importedLon);
reader.readAsText(e.target.files.item(0));
};
}
return false;
});
</script>
The problem that I am facing is that my reader.onload is never fired, in result of which I cannot process my file data. Kindly help me find a solution to make this code running.
P.S: To write this above code, I followed this link: http://jsfiddle.net/W8fME/1650/

I have found the answer of this question myself. The problem was in jquery code in the script tag, correct jquery code is as below:
<script>
$("#filename").change(function(e) {
var ext = $("input#filename").val().split(".").pop().toLowerCase();
if($.inArray(ext, ["csv"]) == -1) {
alert('Upload CSV');
return false;
}
if (e.target.files != undefined) {
var reader = new FileReader();
var csvLines;
var csvValues;
var i;
reader.onload = function(e) {
csvLines = e.target.result.split("\n");
for(i=1; i<csvLines.length; i++){
csvValues = csvLines[i].split(",");
importedLat = csvValues[0];
importedLon = csvValues[1];
markerFunc(importedLat, importedLon);
addLayer();
}
};
reader.readAsText(e.target.files.item(0));
}
return false;
});
</script>

Related

Rewriting file reader in javascript

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

Unable to read image with FileReader (see Update 2)

I am trying read a image file selected by a input[type=file] field with this javascript code:
var reader = new FileReader();
var blob;
reader.onloadend = function (e) {
blob = e.target.result;
}
reader.readAsDataURL(this.files[0]);
but when I run the code in the browser, I am getting this error:
TypeError: Argument 1 of FileReader.readAsDataURL is not an object.
Anyone can see what's wrong here?
UPDATE
this is the code where this snippet is included. SHould given more context about what's causing the error, I hope:
$('#submit').on('click', function(){
var $form = $( 'form.form' ), url = $form.attr( "action" ), str = $form.serialize();
$('input[type=file]').each(function(){
var reader = new FileReader();
var blob;
reader.onloadend = function (e) {
blob = e.target.result;
}
reader.readAsDataURL(this.files[0]);
str = str + "\u0026" + $(this).attr("name") + "=" + blob;
});
var posting = $.post( url, str );
posting.done(function(data){
if(data == "") {
$("#alerta_sucesso").css("display", "block");
} else {
$("#alerta_erro").find("#texto").text(data);
$("#alerta_erro").css("display", "block");
}
});
});
UPDATE 2
I manage to change the code and execute it without errors, but even so I can't store the image inside the variable blob to send this data to the server. The curretn code is this:
$('#submit').on('click', function(){
var $form = $( 'form.form' ), url = $form.attr( "action" ), str = $form.serialize();
var input = $form.find('input[type=file]');
$form.find('input[type=file]').each(function(){
var id = $(this).attr("id");
if(typeof id !== "undefined") {
if(this.files.length > 0) {
var reader = new FileReader();
var blob;
reader.onloadend = function (e) {
blob = e.result;
}
reader.readAsDataURL(this.files[0]);
str = str + "\u0026" + $(this).attr("name") + "=" + blob;
}
}
});
var posting = $.post( url, str );
posting.done(function(data){
if(data == "") {
$("#alerta_sucesso").css("display", "block");
} else {
$("#alerta_erro").find("#texto").text(data);
$("#alerta_erro").css("display", "block");
}
});
});
I assume the problem now it's with the line:
blob = e.result;
Anyone knows what should be the right value for this?
FileReader is asynchronous and the execution happens in a singular thread.
This means when this line is called (I can't see str being defined anywhere, if not, remember to set it to an initial string before appending it, ie. var str = "";):
str = str + "\u0026" + $(this).attr("name") + "=" + blob;
blob is not yet filled with any value yet as it need to wait for the entire function block to finish execution so the code inside the handler can be executed.
You need to build the resulting string from within the callback:
var reader = new FileReader();
reader.onloadend = function() {
str += "&" + $(this).attr("name") + "=" + this.result;
// continue from here ...
};
reader.readAsDataURL(this.files[0]);
But blob is not a blob in this code (or this.result after my changes above), it's a string holding a data-uri at this point. You may need to encode your string first if this is intended to be part of a URI argument (see for example encodeURIComponent - with images as data-uri you may also run into length limitations and will have to use POST).
If you need an actual blob you don't even need to use FileReader - simply use the file object which is also a blob (from this.files[n]).
With the limited information given, if you're trying to show the image in a div or img element, below shows two approaches.
Solution 1
$('input').change(function() {
var fr = new FileReader;
fr.onloadend = function() {
$("#target").attr('src', fr.result);
};
console.log(this.files[0]);
//fr.readAsDataURL(this.files[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file">
<img id="target">
Solution 2
$('input').change(function() {
var fr = new FileReader;
fr.onload = function() {
var img = new Image;
img.onload = function() {
var c = document.getElementById("cvs");
var ctx = c.getContext("2d");
ctx.drawImage(img, 0, 0, 200, 180);
}
img.src = fr.result;
};
console.log(this.files[0]);
fr.readAsDataURL(this.files[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file">
<canvas id="cvs"></canvas>
These would read your file and you can get dynamically the file name and other properties.
So, I finally manage to solve this issue with this approach:
var str = "";
$('input[type=file]').on("change", function(){
var id = $(this).attr("id");
var name = $(this).attr("name");
if(typeof id !== "undefined") {
if(this.files.length > 0) {
reader = new FileReader();
reader.onloadend = function () {
str += "&" + name + "=" + this.result;
}
reader.readAsDataURL(this.files[0]);
}
}
});
$('#submit').on('click', function(){
var $form = $( 'form.form' );
var url = $form.attr( "action" );
str += $form.serialize();
$.post(url, str, function(data){
if(data == "") {
$("#alerta_sucesso").css("display", "block");
} else {
$("#alerta_erro").find("#texto").text(data);
$("#alerta_erro").css("display", "block");
}
});
});
and now the image is being sent to server as a string which can be handled by the PropertyEditorSupport class; this is the thing I am trying make work right now.

I try to upload a image and get that image into base64 format in IE9 using javascript.but i faced issue.please any one help me

This is my javascript code.
if (typeof FileReader !== "undefined") {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#imgprvw' + fieldno).attr('src', e.target.result);
var imgFileSize = input.files[0].size/1024/1024;
if (imgFileSize <= 1) {
var base64image = e.target.result;
console.log(base64image);
}
else {
var base64image = jic.compress(document.getElementById('imgprvw' + fieldno), 90, ext);
}
var imageBase64 = base64image.replace(/^data:image\/(png|jpeg);base64,/, "");
}
}
im using javascript for IE9.i used filereader API and polyfills also. but i didnt get the solution

Word count with javascript

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>

How to detect '\n\r' with FileReader

I'm loading a file on my webapp and I use this function I found on a website to read it:
<script>
function readBlob() {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = 0;
var stop = file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
</script>
The reading works fine but it seems that the "\n\r" is not read and all my lines are stick together.
Is there anything to change in this code to take account of '\n\r' ?
You can solve this problem with CSS only. Demo. MDN.
#byte_content { white-space: pre}

Categories