我要求用户上传和HTML文件,我想将HTML文件的内容转换为字符串。
HTML文件:
<form action="">
<input type="file" name="pic" accept="html" id = "htmlFile">
</form>
JAVASCRIPT
function readTextFile(file) //this is all wrong I think
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
答案 0 :(得分:1)
如果我理解正确,您可以在输入更改后使用FileReader
读取文件,如下所示:
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
alert( "Got the file.n"
+"name: " + f.name + "n"
+"type: " + f.type + "n"
+"size: " + f.size + " bytesn"
+ "contents:" + contents
);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('htmlFile').addEventListener('change', readSingleFile, false);
<form action="">
<input type="file" name="pic" accept="html" id="htmlFile">
</form>