How to read a selected file through Javascript and display an Image preview?

We will start with reading files selected through a

 <input type="file"/>

. This will allow exactly one file to be selected.

<input type="file" multiple="multiple"/>

 

will allow selection of more than one file.

 

The <input type=”file”/> element contains a files collection that contains a collection of all the selected files.

The following code will print a detail of the selected files.

<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="style.css"/>
<title>File Reading</title>
<script>
function processFile()
{
var fl=document.getElementById("f");
var filescollection=fl.files;
var txt=document.getElementById("txtSteps");
var nooffiles=filescollection.length;
txt.value="Files count = " + nooffiles + "\n";
for(var i=0;i<=nooffiles-1;i++)
{
txt.value=txt.value + "File " + (i + 1) + " = " + filescollection[i] + "\n";
}
}
</script>
</head>
<body>
<h2>Files Details</h2><textarea id="txtSteps" class="w3-input" style="height: 150px;">
</textarea><br/>
<input type="file" multiple="multiple" onchange="processFile()" id="f"/>
<br/>
<br/>
<br/>
</body>
</html>

The following code will print more details. Size, name and mime type.

var nooffiles=filescollection.length;
txt.value="Files count = " + nooffiles + "\n";
for(var i=0;i<=nooffiles-1;i++)
{
var file=filescollection[i];
txt.value=txt.value + "File " + (i + 1) + " = " + file + ", size = " + file.size + ",name = " + file.name + ", type=" + file.type + "\n";
}

 

To generate previews of the image files you can simply get a temp src using the createObjectUrl method of the Javascript URL object.

<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="style.css"/>
<title>File Reading</title>
<script>
function processFile()
{
var fl=document.getElementById("f");
var filescollection=fl.files;
var txt=document.getElementById("txtSteps");
var nooffiles=filescollection.length;
txt.value="Files count = " +
nooffiles + "\n";
var idiv=document.getElementById("dImg");
idiv.innerHTML="";
for(var i=0;i<=nooffiles-1;i++)
{
var file=filescollection[i];
txt.value=txt.value + "File " + (i + 1) + " = " + file + ", size = " + file.size + ",name = " + file.name + ", type=" + file.type + "\n";
var src= URL.createObjectURL(file);
idiv.innerHTML+="<img src='" + src + "'/>
<br/>";
}
}
</script>
</head>
<body>
<h2>Files Details</h2>
<textarea id="txtSteps" class="w3-input" style="height: 150px;">
</textarea>
<div id="dImg"></div>
<br/>
<input type="file" multiple="multiple" onchange="processFile()" id="f"/>
<br/>
<br/>
<br/>
</body>
</html>

Try out the html page

File Image Preview

 

Leave a Reply