简体   繁体   中英

How to use HTML5 File API with Unobtrusive JavaScript?

I would like to use the HTML5 File API with unobtrusive JavaScript. But I can only get it working by calling JavaScript functions from the HTML. Is there any way to use the File API with unobtrusive JavaScript?

The File API is not supported by all browsers, but I have tried this in Google Chrome and in Firefox.

From the documentation this works:

<input type="file" id="input" onchange="handleFiles(this.files)">

And I have tried with this unobtrusive JavaScript that doesn't work:

window.onload = function() {
    var input2 = document.getElementById('input2');
    input2.addEventListener('onchange', handleFiles);
}

A complete example is below, and testable on jsFiddle .

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script>
window.onload = function() {
    var input2 = document.getElementById('input2');
    input2.addEventListener('onchange', handleFiles);
}

function handleFiles(e) {
    alert('got files');
}
</script>
</head>
<body>
<h1>Test</h1>
<input type="file" id="input1" onchange="handleFiles(this.files)"/>
<input type="file" id="input2"/>
</body>
</html>

Try:

window.onload = function() {
    var input2 = document.getElementById('input2');
    input2.addEventListener('change', handleFiles,false);
    //                       ^not onchange        ^older firefox needs this
}

jsfiddle here

not onchange but

input2.addEventListener('change', handleFiles);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM