因此,当您在文本编辑器中打开任何文件时,无论是图像,声音文件还是代码,在文本编辑器中,它都会以文本格式提供数据类型,我将如何使用javascript(in一个html文档)打开任何文件并将其作为字符串保存到变量中,如文本编辑器中所示
//something like this
var file = getFile(c:/path/location/goes/here);
document.write(file);
//then it prints the files' text content onto the document
答案 0 :(得分:3)
您可以使用ajax
加载文件,或者如果您想要纯js,请尝试使用以下代码段
function readBlob() {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = 0;
var stop = file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
document.getElementById('byte_range').textContent =
['Read bytes: ', start + 1, ' - ', stop + 1,
' of ', file.size, ' byte file'].join('');
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
<style>
#byte_content {
margin: 5px 0;
max-height: 100px;
overflow-y: auto;
overflow-x: hidden;
}
#byte_range { margin-top: 5px; }
</style>
<input type="file" id="files" name="file" onchange ="readBlob()" />
<div id="byte_range"></div>
<div id="byte_content"></div>