<p> Last opp en fil<br/>
<input type="file" autocomplete="off" id="txtfile" accept="text/html"/>
</p>
<p>
<output id="outtxtfile"> </output>
</p>
Merk accept attributten. Denne sier hvilke filer som vises når vi browser.
Vi kan angi dette på flere måter:
file extension: accept=".text" eller flere file extensions: accept=".text,.csv"
mediatype [1] : accept="text/*", eller accept="text/html" eller accept="image/*,video/*"
Javascript-koden som henter og bruker data:
_demo.js
// load data
function handleFileSelect(evt) {
var f = evt.target.files[0];
found=[];
found.push(encodeURI(f.name),'(',f.type || 'n/a', ') : ',f.size,' bytes')
document.getElementById('outtxtfile').innerHTML = found.join('');
txtType = /text.*/;
if(!f.type.match(txtType)){
document.getElementById('filecontent').innerHTML="bad MIME type";
return;
}
reader=new FileReader();
reader.onload=function(e) {
useIt(reader.result);
}
reader.readAsText(f);
}
//use data
function useIt(T){
// T is a string containing what we have loaded
// Assume it is a HTML-page.
// Build a DOM and count or extract whatever you want
// use any tecnique available for working with the DOM-tree
// accumulate the result here
var result=[];
var parser = new DOMParser();
var doc = parser.parseFromString(T, "text/html");
// get title tag
var title="";
try{
title=doc.getElementsByTagName("title")[0].innerHTML;
}
catch(e){
title=" uten tittel ";
}
result.push("Title: " +title);
// count some other tags
result.push("script-tags: " +doc.getElementsByTagName("script").length);
result.push("style-tags: " +doc.getElementsByTagName("style").length);
result.push("div-tags: " +doc.getElementsByTagName("div").length);
result.push("p-tags: " +doc.getElementsByTagName("p").length);
result.push("nav-tags: " +doc.getElementsByTagName("nav").length);
result.push("h1-tags: " +doc.getElementsByTagName("h1").length);
document.getElementById("filecontent").innerHTML=result.join("<br/>");
}
//eofuse