admin管理员组文章数量:1405149
I'm asking users to upload and HTML file, I would like to convert the contents of the HTML file into a string.
HTML file:
<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);
}
I'm asking users to upload and HTML file, I would like to convert the contents of the HTML file into a string.
HTML file:
<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);
}
Share
edited Jun 9, 2022 at 10:37
Mosh Feu
29.4k18 gold badges93 silver badges141 bronze badges
asked May 25, 2016 at 7:07
Ron Ron
1052 gold badges2 silver badges10 bronze badges
5
- why you need to convert it into string ? – Ranjeet Singh Commented May 25, 2016 at 7:10
- You didn't use jQuery. tag removed. – Raptor Commented May 25, 2016 at 7:10
- @RanjeetSingh I wan't to save the code in my database. – Ron Commented May 25, 2016 at 7:10
- What do you want to achieve? What isn't working? Which errors are you getting? You're missing a lot in your question at the moment.. – SidOfc Commented May 25, 2016 at 7:11
- Possible duplicate of Reading file contents on the client-side in javascript in various browsers – Ivar Commented May 25, 2016 at 7:14
1 Answer
Reset to default 2If I understand you correctly, you can read the file after the input change with FileReader
like this:
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>
Source
本文标签: convert HTML file contents into a string in JavascriptStack Overflow
版权声明:本文标题:convert HTML file contents into a string in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744885143a2630440.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论