Load .txt file into webpage - javascript

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

Related

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");

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

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);

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.

how can i get the height and width of image without page refresh in file tag? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
get image height and width in file tag using javascript
how can i get the height and width of image without page refresh in file tag?
<HTML>
<HEAD>
<TITLE></TITLE>
<script language="javascript">
function getW(){
var theImg = document.getElementById('testimg');
alert(theImg.width);
}
function getH(){
var theImg = document.getElementById('testimg');
alert(theImg.height);
}
</script>
</HEAD>
<BODY>
<input type="file" id="testimg"/>
<input type="button" value="get Width" onclick="getW()"/>
<input type="button" value="get Height" onclick="getH()"/>
</BODY>
</HTML>
i get the image height and width of image using php code, but that time page will be refreshed, without page refresh i get image size but not a height and width....
You can upload file through iframe and after iframe reloaded get image width/height. In modern browsers you can use FileReader API:
<input type="file" id="files" multiple/>
<script type="text/javascript">
function handleFileSelect() {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', theFile.name, '"/>'].join('');
document.body.appendChild(span);
var img = span.getElementsById('img');
img.onload = function() {
alert(img.src, img.offsetWidth, img.offsetHeight);
document.body.removeChild(span);
}
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
There is an excellent post about reading file in javascript.

Categories