html - get a file as a string using javascript -
i have html form upload file.
my goal submit form, check file has xml extension , file string javascript variable.
then, want send post request server using string.
any thought how can that?
my goal submit form, check file has xml extension , file string javascript variable.
i don't think mean want submit form (as in, send server) @ stage.
then, want send post request server using string.
you can on browsers back upwards file api, most modern ones not ie8 or ie9. there's illustration in answer.
basically, file
instance <input type="file">
element's files
list, check name, read it, , post it:
complete example (source) (other post bit, assume know how do):
<!doctype html> <html> <head> <meta charset="utf-8"> <title>example</title> </head> <body> <input type="file"> <button>go</button> <script> (function() { "use strict"; // our input element , our button; in illustration there's // 1 of each, you'd narrow downwards these selectors of course of study var inputelement = document.queryselector("input[type=file]"), button = document.queryselector("button"); if (typeof filereader !== 'function') { alert("the file api isn't supported on browser."); inputelement.style.display = button.style.display = "none"; return; } if (!inputelement.files) { alert("odd, browser has filereader no `files` property on input element."); inputelement.style.display = button.style.display = "none"; return; } button.addeventlistener("click", function() { var file, filename, reader, filedata; // have files? if (inputelement.files.length === 0) { alert("no file chosen"); return; } // first file file = inputelement.files[0]; // name in lower case filename = file.name.tolowercase(); // xml extension? if (filename.substr(-4) !== ".xml") { alert("please take .xml files"); } else { // yes, read reader = new filereader(); reader.onload = function() { // file data, note happens asynchronously filedata = reader.result; // send post data; here, we'll dump out // text displayxml(filedata); }; reader.readastext(file); // or can utilize readasbinarystring } }, false); function displayxml(xmltext) { var pre = document.createelement('pre'); pre.innerhtml = xmltext.replace(/&/g, "&").replace(/</g, "<"); document.body.appendchild(pre); } })(); </script> </body> </html>
javascript html xml file
No comments:
Post a Comment