Unable to read data from multiple files using HTML FileReader - javascript

<input type="file" id="input" multiple onchange="handleFiles(event.target)">
<script language="javascript" type="text/javascript">
<!--
function handleFiles(input)
{
for (i = 0; i < input.files.length; i++)
{
var reader = new FileReader();
reader.onload = function()
{
alert(reader.result)
};
reader.readAsText(input.files[i]);
}
}
//-->
</script>
I am trying to display the contents of some files that I upload. It works fine if I select a single file, but if I select multiple files, only the content of one file is displayed, rest all are blank. What am I doing wrong?

You just need to amend it slighty to do the following:
<input type="file" id="input" multiple onchange="handleFiles(event.target)">
<script language="javascript" type="text/javascript">
function handleFiles(input)
{
for (var i = 0; i < input.files.length; i++) { //for multiple files
(function(file) {
var name = file.name;
var reader = new FileReader();
reader.onload = function(e) {
// get file content
var text = e.target.result;
alert(text)
}
reader.readAsText(file, "UTF-8");
})(input.files[i]);
}
}
</script>
Reference: https://stackoverflow.com/a/9815648/3088780

I think jquery help you easily
HTML:
<script src="jquery-2.2.0.min.js"></script>
<input type="file" multiple="multiple" />
<ul id="output">
</ul>
Jquery:
$('input:file[multiple]').change(
function(e){
console.log(e.currentTarget.files);
var numFiles = e.currentTarget.files.length;
for (i=0;i<numFiles;i++){
fileSize = parseInt(e.currentTarget.files[i].size, 10)/1024;
filesize = Math.round(fileSize);
$('<li />').text(e.currentTarget.files[i].name).appendTo($('#output'));
$('<span />').addClass('filesize').text('(' + filesize + 'kb)').appendTo($('#output li:last'));
}
});
reference from : https://stackoverflow.com/a/7719334/5566169

Related

How can I output multiple lines of a text file in HTML using JS?

This is only the section of the code that I can't solve. The idea is that I open the text file, which I can do, and then I output each line in the div with the id cont. when I open the text file nothing gets output. I don't know why.
<head>
<title>Read Text File</title>
</head>
<body>
<input type="file" name="file" id="file" />
<br>
<div id ="cont"></div>
<script>
document.getElementById('file').onchange = function()
{
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent)
{
var fileContentArray = this.result.split(/\r\n|\n/);
for(var line = 0; line < lines.length-1; line++)
{
document.getElementById("cont").innerHTML = lines[line];
}
}
reader.readAsText(file);
}
</script>
</body>
</html>

Printing output of multiple html files in Javascript

I am trying to print the text multiple files in html. I succeeded in printing the single file. But I am unable to print the text output of a multiple files. Can you please help me in correcting the code?`
<!DOCTYPE html>
<html>
<body>
<h1> Testing programs </h1>
<input type="file" id="fileinput" multiple />
<pre id="file-content"></pre>
<h3>Contents of the file:</h3>
<script type="text/javascript">
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (!files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
displayContents(contents);
};
});
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
function displayContents(contents) {
var element = document.getElementById('file-content');
element.innerHTML = contents;
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false)
</script>
</body>
</html>`
There is no need to use closure in provided snippet. As suggested by gurvinder, use innerHTML +=
if condition should be like if (files) as it will be true if length of files is greater than 0
Try this:
function readMultipleFiles(evt) {
var files = evt.target.files;
if (files) {
for (var i = 0; i < files.length; i++) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
displayContents(contents);
};
r.readAsText(files[i]);
}
} else {
alert("Failed to load files");
}
}
function displayContents(contents) {
var element = document.getElementById('file-content');
element.innerHTML += contents;
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
<h1> Testing programs </h1>
<input type="file" id="fileinput" multiple />
<pre id="file-content"></pre>
<h3>Contents of the file:</h3>
Also refer this fiddle : https://jsfiddle.net/rayon_1990/2cwr4c00/
just replace the displayContents method as
function displayContents(contents) {
var element = document.getElementById('file-content');
element.innerHTML += contents; //observe + before =
}
since it needs to append the files rather than replace the last one

Reading in a text file to display in HTML

I am just working on a web site for fun and I was wondering if you could use JavaScript to read in a local text file and then display it HTML. So for example if I had a text file saved with my project then could I write a function in JavaScript that reads the entire file and then just displays all that text within on the web page?
I've looked around and tried to find something that will do this, but I don't think I fully understand. I have:
function readFile(fileName){
var fileRead = new ActiveXObject('Scripting.FileSystemObject');
text = fileRead.OpenTextFile(fileName, 1, false, 0);
while(!text.AtEndOfSteam){
text += text.ReadLine();
}
text.Close();
}
I don't know if this is will work or do what I want to do. So my question is, how do I use JavaScript to read in a text file, then display the contents of that text file on a webpage in HTML?
You have to use the File API.
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
output.textContent = e.target.result;
});
reader.readAsBinaryString(myFile);
}
});
<input type="file" id="myFile">
<div id="output"></div>
EDIT
After reading your comment, i think this is what you want.
var output = document.getElementById("output");
$("a").on("click", function (e) {
e.preventDefault();
$.ajax(this.href).done(function(data) {
output.textContent = data;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
Link to file
<html>
<head>
<title>reading file</title>
</head>
<body>
<input type="file" id="myFile">
<hr>
<!--<div style="width: 300px;height: 0px" id="output"></div>-->
<textarea style="width:500px;height: 400px" id="output"></textarea>
<script>
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
output.textContent = e.target.result;
});
reader.readAsBinaryString(myFile);
}
});
</script>
</body>
</html>

Javascript- code getting executed before all elements are ready

I have this code in my web. This page takes multiple image files as input and displays them before uploading them to server.
<html>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<body>
<header>
<h1>File API - FileReader</h1>
</header>
<label for="files">Select multiple files: </label>
<input id="files" type="file" multiple/>
<div id='10' style=" width:100px; height:50px; background-color:#006633" onclick="submit_rr(event)">Click</div>
<output id="result" />
</body>
<script language="javascript" type="text/javascript" >
function submit_rr(event){
$('#files').click();
}
$("#files").change(function(){
show_selected(this);
});
function show_selected(input){
for(i = 0;i< input.files.length; i++) {
var reader = new FileReader();
reader.readAsDataURL(input.files[i]);
reader.onload = function (e) {
var img = new Image;
img.onload = function() {
if(img.width>=img.height){
ratio=img.height/img.width;
height=ratio*100;
height_rem=(100-height)/2;
var crt=document.createElement('div');
crt.id="main_some";
crt.className="ind_req_sty";
var Friend="Friend";
crt.innerHTML="<img id="+i+" width='100px' height='"+height+"px' src='"+e.target.result+"'/>";
document.getElementById('10').appendChild(crt);
}else{
ratio=img.width/img.height;
width=ratio*100;
var crt=document.createElement('div');
crt.id='main_req';
crt.className="ind_req_sty";
crt.innerHTML="<img id="+i+" height='100px' width='"+width+"' src='" + e.target.result +"'/>";
document.getElementById('10').appendChild(crt);
}
}
img.src=reader.result;
}
}
}
</script>
</html>
Problem is that, this script executes before all the elements are displayed. As a result only few images are displayed(say 4 out of 10 selected). I tried adding .ready() and .load() but that doesn't work. However if I add an alert('something') all images are displayed without any issue. is there a way I can delay execution so that all images are loaded. I have also tried setTimeout() without any luck. Thanks for your help
If you properly indent your code, you will set that $("#files).change(/*..*/) line is not inside the submit_rr function.
Wrap all your code with
$(function () {
/* your code here */
});
Basically what it does is, creating event handler on dom ready event and after that we are executing our script.
Also, this is a commonly asked question. If you believe the problem you are having is not unique to your case, do your research, if you still cannot find the answer, go ahead and ask.
The link at http://whathaveyoutried.com tells about developers' feelings on answering a repeatedly asked question.
Try putting your <script> tag before the closing </body> tag
Hi After searching .....
I found this works ...
function eecute(event){
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for(var i = 0; i< files.length; i++)
{
var file = files[i];
//Only pics
if(!file.type.match('image'))
continue;
var upload_pic = new FileReader();
upload_pic.addEventListener("load",function(event){
var pic_u = event.target;
var img = new Image;
img.src=pic_u.result;
if(img.width>=img.height){
var div = document.createElement("cover");
div.innerHTML= "<div style='text-align: center; margin-top:8px; width:150px;margin-right:5px; height:150px;float:left'><img style='display:inline-block;' width='150' src='" + pic_u.result + "'/></div>";
output.insertBefore(div,null);
}else{
var div = document.createElement("cover");
div.innerHTML="<div style='text-align: center ;margin-top:8px;width:150px; margin-right:5px; height:150px;float:left'><img style='display:inline-block; margin:auto;' src='" + pic_u.result + "'height='150' /></div>";
output.insertBefore(div,null);
}
});
//Read the image
upload_pic.readAsDataURL(file);
}
}

Insert value to input / JavaScript

I have the following JS / HTML code:
<input type="text" class="file" name="file_info" id="file_info">
<div class="file_upload">
<input type="file" id="file_upload" onchange="name();">
</div>
<script>
function name() {
var fileName = document.getElementById("file_upload").value;
var fnSplit = fileName.split(/[\/\\]/);
fileName = fnSplit[fnSplit.length - 1];
document.getElementById('file_info').innerHTML = 'Fred Flinstone';
}
</script>
I want that after I upload file, the file-name will shown in the tput text, but this cide doesn't work.
How can I fix it?
Update : The file name should be inside the input text
Move your script element before the input element. You had better put the script element inside your head like this
Demo
Have update the answer!
You can try this code:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var fileName =document.getElementById("file_upload").value;
var fnSplit = fileName.split(/[\/\\]/);
fileName = fnSplit[fnSplit.length - 1];
document.getElementById('file_info').value = fileName
}
</script>
</head>
<body>
<input type="text" class="file" name="file_info" id="file_info">
<div class="file_upload">
<input type="file" id="file_upload" onchange="myFunction();">
</div>
</body>
</html>
Do it like this:
HTML
<div class="file_upload">
<input type="file" id="file_upload">
</div>
<div id="file_info"></div>
JS
function name(file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function (event) {
document.getElementById('file_info').innerHTML = "Filename: " + file.name + "\nContent: " + event.target.result;
};
reader.onerror = function () {
alert('Unable to read ' + file.name);
};
}
document.getElementById('file_upload').onchange = function () {
name(this.files[0]);
};
DEMO

Categories

Resources