JS FileReader: Read CSV from Local File & jquery-csv - javascript

I have a CSV file in the same directory as an html page, and I'd like to use FileReader to read the file contents into a jquery-csv's To Arrays function, but I can't seem to get it to work properly. I think I understand the asynchrony of this task, but have i depicted it correctly? Here, I'm trying to output the 2nd cell in the 2nd column. Thanks for any help.
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['timeline']}]}"></script>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="jquery.csv-0.71.js"></script>
<script type="text/javascript">
var reader = new FileReader();
reader.onload = function(e) {
var text = e.target.result;
var data = $.csv.toArrays(text);
document.write(data[1][1]);
}
reader.readAsText('data.csv');
</script>

Here's a working demo provided by jquery-csv
<html>
<head>
<meta charset="utf-8" />
<title>Demo - CSV-to-Table</title>
</head>
<body>
<div id="inputs" class="clearfix">
<input type="file" id="files" name="files[]" multiple />
</div>
<hr />
<output id="list">
</output>
<hr />
<table id="contents" style="width:100%; height:400px;" border>
</table>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://evanplaice.github.io/jquery-csv/src/jquery.csv.min.js"></script>
<script>
$(document).ready(function() {
if(isAPIAvailable()) {
$('#files').bind('change', handleFileSelect);
}
});
function isAPIAvailable() {
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
return true;
} else {
// source: File API availability - http://caniuse.com/#feat=fileapi
// source: <output> availability - http://html5doctor.com/the-output-element/
document.writeln('The HTML5 APIs used in this form are only available in the following browsers:<br />');
// 6.0 File API & 13.0 <output>
document.writeln(' - Google Chrome: 13.0 or later<br />');
// 3.6 File API & 6.0 <output>
document.writeln(' - Mozilla Firefox: 6.0 or later<br />');
// 10.0 File API & 10.0 <output>
document.writeln(' - Internet Explorer: Not supported (partial support expected in 10.0)<br />');
// ? File API & 5.1 <output>
document.writeln(' - Safari: Not supported<br />');
// ? File API & 9.2 <output>
document.writeln(' - Opera: Not supported');
return false;
}
}
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var file = files[0];
// read the file metadata
var output = ''
output += '<span style="font-weight:bold;">' + escape(file.name) + '</span><br />\n';
output += ' - FileType: ' + (file.type || 'n/a') + '<br />\n';
output += ' - FileSize: ' + file.size + ' bytes<br />\n';
output += ' - LastModified: ' + (file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() : 'n/a') + '<br />\n';
// read the file contents
printTable(file);
// post the results
$('#list').append(output);
}
function printTable(file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result;
var data = $.csv.toArrays(csv);
var html = '';
for(var row in data) {
html += '<tr>\r\n';
for(var item in data[row]) {
html += '<td>' + data[row][item] + '</td>\r\n';
}
html += '</tr>\r\n';
}
$('#contents').html(html);
};
reader.onerror = function(){ alert('Unable to read ' + file.fileName); };
}
</script>
</body>
</html>
Disclaimer: I'm the author of jquery-csv

It's not going to work.You have no permissions to read files with javascript from the browser. The only way to deal with it is to create an input[type=file] tag and add onChange event to it. For example:
document.getElementById('fileupload').addEventListener('change', function (e) {
var files = e.target.files;
//proceed your files here
reader.readAsText(files[0]);
}, false);

Related

File Input stopped working in Instagram in-app browser (Android only)

input type="file" stopped working in Android Instagram in-app browser recently. It was working fine earlier. It still works fine in iOS. I also tested it in Facebook in-app browser which also works fine on both Android and iOS.
Here is my simple test codes.
<!DOCTYPE html>
<html>
<head>
<title>File Validation</title>
</head>
<body>
<p>
<input type="file" id="file" onchange="checkFileSize()" />
</p>
<p id="size"></p>
</body>
<script>
var checkFileSize = function() {
var input = document.getElementById('file');
if (input.files.length > 0) {
for (var i = 0; i < input.files.length; i++) {
var fsize = input.files[i].size;
var file = Math.round((fsize / 1024));
document.getElementById('size').innerHTML = '<b>' + file + '</b> KB';
}
}
}
</script>
</html>
It just prints the file size on selection of a file. I have also uploaded the html to my Amazon S3 for easier testing. Here is the page link - https://virtueplanet.s3.amazonaws.com/testfile/index.html
If you open the link in Instagram in-app browser and select a file from your phone then it always returns the file size as zero (0). I also tried to read the file using Filereader which also fails.
var input = document.getElementById('file');
if (input.files.length > 0) {
for (var i = 0; i < input.files.length; i++) {
var reader = new FileReader();
reader.onload = function(e) {
alert('Image loaded.');
}
reader.onerror = function() {
alert(reader.error.message);
}
reader.readAsDataURL(input.files[i]);
}
}
It appears to be bug in the recent Instagram App update for Android. Any help will be highly appreciated.

Load .txt file into webpage

I am trying to have a user click on a "load file" button to choose a file for the webpage. But I can't seem to get the actual file, just the name and when it was last modified. I need to run some JS code on that file, so I just need the actual text. I don't need to put it in the web page, but I just thought that would be a good way to display it. Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onclick="update_loc(event)"">
<center><canvas width="400" height="400" id="myCanvas" style="border: 1px solid; border-color: #000000"></canvas></center>
<script src="./js.js"></script>
<input type="file" id="myFile">
<p id="output">YO</p>
</body>
</html>
And my JS:
var reader;
var file;
setTimeout(test_file, 500);
function test_file() {
setTimeout(test_file, 500);
file = document.getElementById("myFile").files[0];
console.log(document.getElementById("myFile").files);
reader = new FileReader();
reader.onload = function (e) {
var textArea = document.getElementById("output");
textArea.value = e.target.result;
};
reader.readAsText(file);
}
I could not figure out how to copy and paste the chrome log, but I just got the file name and time in a "FileList" object.
Try this:
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
For more info about how to read and manipulate those files (in this examples is for multiple files) check this url

How to make a drag and drop HTML file reader

I am working on a small HTML file API application. This application can support users to drag, drop a file and read the file content. However, I found I either can make the drag, drop and read the file info part or using HTML upload feature to let users upload a file and read the file content.
Please see the example here: https://jsfiddle.net/tqcuor5g/
I just want the user can drop a file into a drop zone and the app can read its content and show in the text area.
My question is how can I make the application support drag, drop and read the file content at the same time? Thank you in advance!
Source code:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body
{
font-size:18pt;
}
#filedrop
{
width: 300px;
height: 200px;
color: Gray;
border: 10px dashed #9a9a9a;
}
</style>
<title>Reading a Text File</title>
<script type="text/javascript">
function init() {
var bHaveFileAPI = (window.File && window.FileReader);
if (!bHaveFileAPI) {
alert("This browser doesn't support the File API");
return;
}
document.getElementById("filedrop").addEventListener("drop", onFilesDropped);
document.getElementById("filedrop").addEventListener("dragover", onDragOver);
document.getElementById("fileElem").addEventListener("change", onFileChanged);
}
function onFileChanged(theEvt) {
var thefile = theEvt.target.files[0];
console.log(thefile);
// check to see if it is text
if (thefile.type != "text/plain") {
document.getElementById('filecontents').innerHTML = "No text file chosen";
return;
}
var reader = new FileReader();
reader.onload = function (evt) {
var resultText = evt.target.result;
document.getElementById('filecontents').innerHTML = resultText;
}
reader.readAsText(thefile);
}
function onDragOver(theEvt) {
theEvt.stopPropagation();
theEvt.preventDefault();
}
function onFilesDropped(theEvt) {
theEvt.stopPropagation();
theEvt.preventDefault();
var files = theEvt.target.files;
document.getElementById('filedata').innerHTML = "";
for (var i = 0; i <= files.length; i++) {
var fileInfo = "<p>File name: " + files[i].name + "; size: " + files[i].size + "; type: " + files[i].type + "</p>";
document.getElementById('filedata').innerHTML += fileInfo;
}
}
window.addEventListener("load", init);
</script>
</head>
<body>
<h1>Using Drag and Drop</h1>
<p>Drop files here: </p>
<div id="filedrop"></div>
<p>File Information: </p>
<div id="filedata"></div>
<h1>Reading File Data as Text</h1>
<form action="">
<label>Select a file: </label>
<input type="file" name="files" id="fileElem" />
</form>
<p>File contents: </p>
<textarea cols="80" rows="10" id="filecontents"></textarea>
</body>
</html>

File Select/File API - Sending files to Embedded PDFObject

So I'm trying to use file select (or file API) to select file from desktop and send it to an embedded PDF viewer in my HTML Doc. I've tried a lot of different ways with my limited knowledge to push the file from the file-api to the PDFObject and nothing seems to work. I'm not sure if it's not able to do this or if I'm just doing it wrong in many different ways.
<head>
<link href="http://pdfobject.com/css/examples.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://pdfobject.com/scripts/pdfobject.js"></script>
<script type="text/javascript">
window.onload = function (){
var myPDF = new PDFObject(handleFileSelect).embed();
// ORIGINALLY var myPDF = new PDFObject({ URL: "location" }).embed();
};
</script>
</head>
<body>
<div id="pdf">It appears you don't have Adobe Reader or PDF support in this web browser. Click here to download the PDF</div>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
Can I use file select/file api to select and push a document to the PDFObject viewer or does it not allow that sort of connection?
Simply retrieve the url of the file by creating one:
url=window.URL.createObjectURL(inputFile);
and then embed the file by giving PDFObject this url:
PDFObject.embed(url, "#fileContainer");

Javascript: Persist file upload between redirects

Since there were no answers to this question:
Resumable.js: Persist file uploading between redirects and browser restarts
I am working on a workaround to let users upload their files in a separate popup, while they browse other pages. This is how I am passing my file objects to the popup window:
index.html:
<ol id="chosenFilesList"></ol>
Select files
<br>
<br>
<br>
Upload
<script src="resumable.js"></script>
<script>
var fileArr = [];
function displaySelectedFiles() {
var fileList = '';
for (var i = 0; i < fileArr.length; i++)
if(fileArr[i])
fileList += '<li>' + fileArr[i].name + '</li><a style="cursor: pointer;" onclick="removeFile(' + fileArr[i] + ');">Remove</a>';
//localStorage.setItem('fileArr', fileArr);
document.getElementById('chosenFilesList').innerHTML = fileList;
}
var r = new Resumable({
target:'test.html'
});
r.assignBrowse(document.getElementById('browseButton'));
r.on('fileSuccess', function(file){
console.debug('fileSuccess',file);
});
r.on('fileProgress', function(file){
console.debug('fileProgress', file);
});
r.on('fileAdded', function(file, event){
//r.upload();
fileArr.push(file.file);
displaySelectedFiles();
console.debug('fileAdded', event);
});
r.on('filesAdded', function(array){
//r.upload();
displaySelectedFiles();
console.debug('filesAdded', array);
});
r.on('fileRetry', function(file){
console.debug(file);
});
r.on('fileError', function(file, message){
console.debug('fileError', file, message);
});
r.on('uploadStart', function(){
console.debug('uploadStart');
});
r.on('complete', function(){
console.debug('complete');
});
r.on('progress', function(){
console.debug('progress');
});
r.on('error', function(message, file){
console.debug('error', message, file);
});
r.on('pause', function(){
console.debug('pause');
});
r.on('cancel', function(){
console.debug('cancel');
});
var popupWindow;
var addFiles = function() {
for (var i = 0; i < fileArr.length; i++) {
if(fileArr[i])
popupWindow.r.addFile(fileArr[i]);
}
//popupWindow.startUpload();
window.location.reload();
setTimeout('popupWindow.focus()', 1);
};
document.getElementById('uploadButton').addEventListener('click', function(evt) {
popupWindow = window.windowPop('', 900, 500);
if(popupWindow.location.href.indexOf('test.html') === -1) {
popupWindow.location.href = 'test.html';
setTimeout(function(){
popupWindow.onload = addFiles;
addFiles();
}, 300);
} else {
addFiles();
}
});
function windowPop(url, width, height) {
var leftPosition, topPosition;
//Allow for borders.
leftPosition = (window.screen.width / 2) - ((width / 2) + 10);
//Allow for title and status bars.
topPosition = (window.screen.height / 2) - ((height / 2) + 50);
//Open the window.
return window.open(url, "Window2", "status=no,height=" + height + ",width=" + width + ",resizable=yes,left=" + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY=" + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no");
}
</script>
test.html:
<!DOCTYPE html>
<html>
<head>
<title>Resumable.js - Multiple simultaneous, stable and resumable uploads via the HTML5 File API</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="frame">
<h3>Demo</h3>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="resumable.js"></script>
<div class="resumable-error">
Your browser, unfortunately, is not supported by Resumable.js. The library requires support for the HTML5 File API along with file slicing.
</div>
<div class="resumable-drop" ondragenter="jQuery(this).addClass('resumable-dragover');" ondragend="jQuery(this).removeClass('resumable-dragover');" ondrop="jQuery(this).removeClass('resumable-dragover');">
Drop video files here to upload or <a class="resumable-browse"><u>select from your computer</u></a>
</div>
<div class="resumable-progress">
<table>
<tr>
<td width="100%"><div class="progress-container"><div class="progress-bar"></div></div></td>
<td class="progress-text" nowrap="nowrap"></td>
<td class="progress-pause" nowrap="nowrap">
<img src="resume.png" title="Resume upload" />
<img src="pause.png" title="Pause upload" />
</td>
</tr>
</table>
</div>
<ul class="resumable-list"></ul>
<script>
var r = new Resumable({
target:'/java-example/upload',
chunkSize:1*1024*1024,
simultaneousUploads:4,
testChunks: true,
throttleProgressCallbacks:1,
method: "octet"
});
// Resumable.js isn't supported, fall back on a different method
if(!r.support) {
$('.resumable-error').show();
} else {
// Show a place for dropping/selecting files
$('.resumable-drop').show();
r.assignDrop($('.resumable-drop')[0]);
r.assignBrowse($('.resumable-browse')[0]);
// Handle file add event
r.on('fileAdded', function(file){
// Show progress pabr
$('.resumable-progress, .resumable-list').show();
// Show pause, hide resume
$('.resumable-progress .progress-resume-link').hide();
$('.resumable-progress .progress-pause-link').show();
// Add the file to the list
$('.resumable-list').append('<li class="resumable-file-'+file.uniqueIdentifier+'">Uploading <span class="resumable-file-name"></span> <span class="resumable-file-progress"></span>');
$('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-name').html(file.fileName);
// Actually start the upload
r.upload();
console.log(file);
});
r.on('pause', function(){
// Show resume, hide pause
$('.resumable-progress .progress-resume-link').show();
$('.resumable-progress .progress-pause-link').hide();
});
r.on('complete', function(){
// Hide pause/resume when the upload has completed
$('.resumable-progress .progress-resume-link, .resumable-progress .progress-pause-link').hide();
});
r.on('fileSuccess', function(file,message){
// Reflect that the file upload has completed
$('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html('(completed)');
});
r.on('fileError', function(file, message){
// Reflect that the file upload has resulted in error
$('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html('(file could not be uploaded: '+message+')');
});
r.on('fileProgress', function(file){
// Handle progress for both the file and the overall upload
$('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html(Math.floor(file.progress()*100) + '%');
$('.progress-bar').css({width:Math.floor(r.progress()*100) + '%'});
});
}
</script>
</div>
</body>
</html>
I just added / modified https://github.com/23/resumable.js/tree/master/samples/java sample HTML files.
I am just getting all the file objects from file selectors and uploading them in a separate window using resumable.js (I don't think library is important here). It works flawlessly on Chrome and Firefox.
The problem with this approach is, in IE 11- (as far as I tested), the file uploading stops as soon as user is redirected to another page.
Can anybody please tell me how can I make it work in all browsers (hopefully, using pure javascript)?
Also, it will be a lot helpful, if I can just persist an upload between browser restarts as well.

Categories