gpt4 book ai didi

javascript - 我如何在javascript中打开任何类型的文件并将其保存为字符串

转载 作者:行者123 更新时间:2023-11-30 11:23:54 25 4
gpt4 key购买 nike

因此,当您在文本编辑器中打开任何文件时,无论是图像文件、声音文件还是一段代码,在文本编辑器中它都会显示文本格式的数据类型,我将如何使用 javascript(在一个 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

最佳答案

您可以使用 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>

关于javascript - 我如何在javascript中打开任何类型的文件并将其保存为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48761407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com